Objective
During an interview, an interviewer once said that the focus of the mobile app is on the connection between the device and the network, which enables the user interface and the server to interact with the data. Like wired Internet, wireless Internet can also use HTTP to access the network, in Android, there are two ways to implement HTTP communication: One is implemented through Httpurlconnextion, the other is implemented through HttpClient.
HttpURLConnection class
There are two ways to communicate using HttpURLConnection:get () and post ().
The default is to send a get () request, which can be passed after the URL when sending a GET request "? Parameter name = argument value "is passed, and multiple parameters are separated by commas, such as:
String target= "http://192.168.1.104:8080/blog/index.jsp?content=" +base64 (Contenttext.gettext (). toString (). Trim ( ));
The use of the Get method for data communication is implemented primarily through the following code:
Url=NewURL (target);//Create a URL object//because HttpURLConnection is an abstract class, you can instantiate an object by OpenConnection//with HttpURLConnection, a GET request is sent by defaultHttpURLConnection urlconn=(HttpURLConnection) url.openconnection (); //the above to send content to the server//The following reads the content from the server if(Urlconn.getresponsecode () = =HTTPURLCONNECTION.HTTP_OK) {InputStreamReader in=NewInputStreamReader (Urlconn.getinputstream ());//read content from the serverBufferedReader buffer=NewBufferedReader (in);//get input Stream object and convert to text//read input stream content by looping through rowsString inputline=NULL; while((Inputline=buffer.readline ())! =NULL) {result+=inputline+ "\ n"; } in.close ();//close character input stream object} urlconn.disconnect ();//Disconnect Connection
It is necessary to note that Url.openconnection () just established an HTTP connection, until Urlconn.getinputstream () actually sends the HTTP request.
The use of the Post () method is primarily implemented by the following code:
Url=NewURL (target);//Create a URL object//because HttpURLConnection is an abstract class, you can instantiate an object by OpenConnectionHttpURLConnection urlconn=(HttpURLConnection) url.openconnection (); Urlconn.setrequestmethod ("POST");//specifies that a request is made using the Post methodUrlconn.setdoinput (true);//allow data to be written to the connectionUrlconn.setdooutput (true);//allow data to be read from the connectionUrlconn.setusecaches (false);//disable caching, Post requests cannot use cacheUrlconn.setrequestproperty ("Content-type", "application/x-www-form-urlencoded");//set content type to URIDataOutputStream out=NewDataOutputStream (Urlconn.getoutputstream ());//Get output streamString param= "Content" +urlencoder.encode (Contenttext.gettext (). toString (), "Utf-8"); Out.writebytes (param);//write data to the data output streamOut.flush ();//flush output stream, output cacheOut.close ();//turn off the output stream//the above to send content to the server//The following reads the content from the server if(Urlconn.getresponsecode () = =HTTPURLCONNECTION.HTTP_OK) {InputStreamReader in=NewInputStreamReader (Urlconn.getinputstream ());//read content from the serverBufferedReader buffer=NewBufferedReader (in);//get input Stream object and convert to text//read input stream content by looping through rowsString inputline=NULL; while((Inputline=buffer.readline ())! =NULL) {result+=inputline+ "\ n"; } in.close ();//close character input stream object} urlconn.disconnect ();//Disconnect Connection
In the post mode, the HTTP body is written by OutputStream , and OutputStream is actually a string stream, and the data written to it is not immediately sent to the network, but is stored in the memory buffer. When OutputStream is closed, the body is generated based on what you entered. The difference in how the parameter is passed is also the biggest distinction between the get () method and the post () method.
Whether using the Get () method or the post () method, you need to open a new sub-thread for network data transfer and send and process the message via handler:
//Create a new thread for sending and reading information NewThread (NewRunnable () {@Override Public voidrun () {//TODO auto-generated Method StubUrlgetsend ();//send text content to the server and read the results from the server//using Obtainmessage to get empty message objects from the message poolMessage m=Handler.obtainmessage (); Handler.sendmessage (m); }}). Start ();
handler=New handler () { @Override publicvoid handlemessage ( Message msg) { if(result!=null) { resulttv.settext (result); // updating the interface in the UI thread Contenttext.settext (""); } Super . Handlemessage (msg); } ;
The creation and use of threads, the use of handler, and the relationship with MessageQueue will be described in a separate article.
HttpClient class
HttpURLConnection is typically used to submit requests on a simple page and get a response from the server, and for more complex internet operations, httpclient can be better implemented. The two implementations are in fact very much connected, httpclient the input and output stream operations in the HttpURLConnection class, encapsulated as HttpGet, HttpPost, and httprespense classes, thus reducing the complexity of the operation. Where the HttpGet class is used to send a GET request, the HttpPost class is used to send a POST request, and the Httprespense class represents the object that handles the response.
The get () request can be implemented with the following code:
String target= "http://192.168.1.104:8080/blog/index.jsp?content=" +Base64 (Contenttext.gettext (). toString (). Trim ()); HttpClient HttpClient=NewDefaulthttpclient ();//Create a HttpClient objectHttpGet httprequest=NewHttpGet (target);//Create a HttpGet Connection objectHttpResponse HttpResponse; Try{HttpResponse=httpclient.execute (HttpRequest);//Specify HttpClient Request if(Httpresponse.getstatusline (). Getstatuscode () = =HTTPSTATUS.SC_OK) {Result=entityutils.tostring (Httpresponse.getentity ());//converting the returned data } Else{result= "Fail"; } }
The Get () method of the relative HttpURLConnection class is much easier to operate.
The post () request can be implemented with the following code:
String target= "http://192.168.1.104:8080/blog/index.jsp"; HttpClient HttpClient=Newdefaulthttpclient (); //instantiate an object directly using the HttpPost class without specifying the request modeHttpPost httprequest=NewHttpPost (target);//Create a HttpPost Connection objectHttpResponse HttpResponse; //Save the arguments to be passed to the list collectionList<namevaluepair> params=NewArraylist<namevaluepair>(); Params.add (NewBasicnamevaluepair ("Content", Contenttext.gettext (). toString ())); Try{httprequest.setentity (NewUrlencodedformentity (params, "utf-8"));//Setting the Encoding methodHttpresponse=httpclient.execute (HttpRequest);//Execute httpclient Request if(Httpresponse.getstatusline (). Getstatuscode () = =HTTPSTATUS.SC_OK) {Result=entityutils.tostring (Httpresponse.getentity ());//converting the returned data } Else{result= "Fail"; } }
In the post () method, you can add a request parameter by using the SetParams () method, or you can call the setentity () implementation.
Subsequent:
There is a lot of knowledge about HTTP, and then we will do more in-depth study later.