This article introduces the use of HTTP GET and Post methods for network communication, which describes using httpclient httpget and network communication.
First, make sure that the current project already contains Apache support libraries
Download Link: http://hc.apache.org/downloads.cgi
If the library file is not included, first copy all of the. jar packages from the Lib in the file downloaded above to the project's Libs, and select the Addaslibrary in the engineering directory of the Android studio.
HttpGet Communication
The steps above can be used to create a new httpclient first:
HttpClient client=new defaulthttpclient ();
Create a new HttpGet, the parameter is a URL string:
HttpGet httpget=new httpget ("http://fanyi.youdao.com/openapi.do?keyfrom=skyhttpgettest&key=545323935& Type=data&doctype=json&version=1.1&q=hello ");
by Httpclient.execute (HttpGet), the GET request is sent, the argument is Httpurirequest, and HttpGet and httppost inherit it, so the next HttpPost sends the request in the same way, The method returns a HttpResponse;
HttpResponse Responnse=client.execute (HttpGet);
Previously, when communicating with HTTP GET and post, the HttpURLConnection input stream was obtained to read the data, that is, Connection.getinputstream (), Use HttpClient to obtain the return data by first obtaining a returned HttpResponse object and obtaining the data entity, then reading the contents of the Data entity: GetContent () returns an input stream InputStream:
Httpentity entity=response.getentity ();
InputStream in=entity.getcontent ();
Next, the IO operation is used to read the data ...
HttpPost Communication
As in the previous HttpGet way, new httpclient
New HttpPost:
HttpPost httppost=new httppost ("http://fanyi.youdao.com/openapi.do");
Notice the difference from the previous HttpGet way, the previous HttpGet will submit the form data directly behind the URL, and HttpPost is not directly written in the back.
Now that the form data is not placed behind the URL, our setup httppost the form content, and instead of getting a outputstream write data like the previous HTTP POST method, we set up a httpentity entity
Build a ArrayList, type Basicnamevaluepair (key-value pair) that contains the form data
List.add (new Basicnamevaluepair ("Keyfrom", " Skyhttpgettest "));
List.add (New Basicnamevaluepair ("Key", "545323935"));
List.add (New Basicnamevaluepair ("type", "data"));
List.add (New Basicnamevaluepair ("doctype", params[0));
List.add (New Basicnamevaluepair ("version", "1.1"));
List.add (New Basicnamevaluepair ("Q", params[1));
Httppost.setentity (new urlencodedformentity (list));
Then and Httpgethttpclient execute:
HttpResponse Response=client.execute (httppost);
Httpentity entity=response.getentity ();
InputStream in=entity.getcotent ();
//... Data read operations