---restore content starts---
This essay is a small example of some online, I have to add some comments after learning. Vegetable chicken programmer, low level, please point out if you have any questions.
HttpClient is a packaged HTTP protocol toolkit that is simpler and more functional than httpconection.
HttpClient has two important methods, a post, a get, as the name implies that one is used to send data, get the return value, and a direct request address to get the return value.
Here are a few examples of post and get:
1.get Small instance.
Public class Gggggg {
Public String doget () {
String url= "HTTP://WWW.123.COM/XXXX/CCC";
String result = "";
httpget httprequst = new HttpGet (URL);
try{
HttpResponse HttpResponse = new Defaulthttpclient (). Execute (httprequst);//execute Get return value
if (Httpresponse.getstatusline (). Getstatuscode () ==200) {
httpentity httpentity = httpresponse.getentity ();//Receive Message
result = entityutils.tostring (httpentity);//Conversion format
} else
Httprequst.abort ();//Termination
}catch (clientprotocolexception e) {
e.printstacktrace ();
result = E.getmessage (). toString ();
} catch (IOException e) {
e.printstacktrace ();
result = E.getmessage (). toString ();
}
return result;
}
}
This example is a very simple get instance, the data that is taken out is only a conversion type of processing. Note Httprequst.abort () here, when the found returned status Getstatuscode () is not 200 Yes, is an error, to close the stream.
2.get Small instance.
Public class HHH {
Public static void Main (string[] args) throws Clientprotocolexception, ioexception{
HttpClient HC = new defaulthttpclient ();//new Interface Subclass
httpget hg = new HttpGet ("http:www.baidu.com");//Package Request address
HttpResponse res = Hc.execute (Hg);//Send request to get return value
httpentity entity = res.getentity ();//Get message Contains server response content
if (entity!=null) {//Judgment message is not empty
InputStream INSM = entity.getcontent ();//get content with streams
string str = convertstreamtostring (INSM);//inputstream converted to string
Hg.abort ();//http Request terminated
}
}
Public static String convertstreamtostring (InputStream is) {//conversion
BufferedReader reader = new BufferedReader (new InputStreamReader (IS));
StringBuilder sb = new StringBuilder ();
String line = null;
try{
While (line = Reader.readline ())!=null) {
sb.append (line+ "\ n");
}
} catch (IOException e) {
e.printstacktrace ();
}finally{
try{
is.close ();
}catch (IOException e) {
e.printstacktrace ();
}
}
return sb.tostring ();
}
}
This example, like the example above, simply converts the data in the stream to a string type.
Small instance of 3.post method
public class Pppp {
Public String Hpost () {
String url = "http://123.456.789.1";
String result = "";
HttpPost httprequset = new HttpPost (URL);//Instantiate HTTP interface
List <NameValuePair> params = new arraylist<namevaluepair> ();//Instantiate an HTTP array
Params.add (New Basicnamevaluepair ("Content", "I am So Cool"));//Put Parameters
try{
httprequset.setentity (New Urlencodedformentity (params,http. Utf_8)); Passing parameters and character encodings to the message
HttpResponse HttpResponse = new Defaulthttpclient (). Execute (httprequset);//execute or return value
if (Httpresponse.getstatusline (). Getstatuscode () = = () {
httpentity httpentity = httpresponse.getentity ();//Get Return message
result = entityutils.tostring (httpentity);//Convert to string format
}
} catch (Unsupportedencodingexception e) {
e.printstacktrace ();
result = E.getmessage (). toString ();
}
catch (Clientprotocolexception e) {
e.printstacktrace ();
result = E.getmessage (). toString ();
}
catch (IOException e) {
e.printstacktrace ();
result = E.getmessage (). toString ();
}
return result;
}
}
If you use the HttpPost method to submit an HTTP POST request, you need to set the request parameters using the Setentity method of the HttpPost class. Parameters must be stored with the namevaluepair[] array
Post method Note httprequset.setentity (new Urlencodedformentity (params,http. Utf_8), urlencodedformentity method Baidu means to construct a new urlencodedformentity with a list of specified parameter encodings. I understand that the character encoding corresponding to the params is set to Http.utf_8. Usually the characters returned using the POST request, especially when the Chinese characters are garbled, please check the settings here, instead of the interface corresponding to the character encoding.
4.post Small Instance
Public class PPP {
Public static void Main (string[] args) {//post I'm going to pass the arguments
String name = "Joe";
String age = "n";
String content = "cool";
String ret = sendsms (name,age,content);//Call execution Method
System.out.println (ret);
if (Ret.indexof ("failed") <0) {
System.out.print ("sent successfully");
}
else{
System.out.print ("Send Failed");
}
}
Public static String sendsms (string name,string age,string content) {//Receive parameter execution
HttpClient HttpClient = new Defaulthttpclient ();//new sub-class
String url = "Http://192.168.0.1/aaaaa/sedsms";
HttpPost httppost = new HttpPost (URL);//Package Send address
String res = ""; Defining return Values
try {
list<namevaluepair> namevaluepairs = new arraylist<namevaluepair> ();//Instantiate Namevaluepair parameters
jsonobject jobj = new Jsonobject ();//New JSON object drop parameters
jobj.put ("name", name);
jobj.put ("age", age);
jobj.put ("content", content);
Namevaluepairs.add (New Basicnamevaluepair ("MSG", Getstringfromjson (Jobj)));//go to Namevaluepair
Httppost.addheader ("Content-type", "application/x-www-form-urlencoded");//Set HTTP message properties
httppost.setentity (New urlencodedformentity (Namevaluepairs, "UTF-8"));//Incoming message, set text encoding
HttpResponse response = Httpclient.execute (HttpPost);//execute Get return value
if (Response.getstatusline (). Getstatuscode () = = 200) {//Return 200 status down execution
string conresult = Entityutils.tostring (Response.getentity ());//Get return message converted to String format
jsonobject sobj = new Jsonobject ();//New JSON
sobj = Sobj.fromobject (Conresult);//The resulting string object content is converted to a JSON object
String result = sobj.getstring ("result");//Use getString method or get value
String code = sobj.getstring ("code");
if (result.equals ("1")) {
res + = "Send Success";
}else{
res + = "Send failed," +code;
}
} else {
String err = Response.getstatusline (). Getstatuscode () + "";
res + = "Send failed:" +ERR;}
}catch (clientprotocolexception e) {
e.printstacktrace ();
}catch (IOException e) {
e.printstacktrace ();
}
return res;
}
private static String Getstringfromjson (Jsonobject adata) {//spelling parameters
stringbuffer sb = new StringBuffer ();
Sb.append ("{");
For (Object Key:adata.keySet ()) {
sb.append ("\" "+key+" \ ": \" "" +adata.get (key) + "\", ");
}
String RTN = sb.tostring (). substring (0, sb.tostring (). Length ()-1) + "}";
return RTN;
}
}
list<namevaluepair> namevaluepairs = new arraylist<namevaluepair> (); The Namevaluepair array in the method is a data store type for a specific key value in HttpClient, similar to the form form.
Summarize
Use of HttpClient requires the following 6 steps: 1. Creates an instance of HttpClient. 2. Create an instance of some kind of connection method, HttpPost, HttpGet, GetMethod, and so on. 3. Invoke the Execute method of the created instance in the first step to execute the created instance in the second step. 4. Read response. 5. Release the connection. The connection close (), abort () must be released regardless of the success of the execution method. 6. Process the content after it is received. You can refer to the following when you need to set parameters for the request:
Httpparams httpparameters = new Basichttpparams ();
Httpconnectionparams.setconnectiontimeout (httpparameters, 10*); Set Request Timeout 10 seconds
Httpconnectionparams.setsotimeout (httpparameters, 10*1000); //Set wait data timeout 10 seconds
Httpconnectionparams.setsocketbuffersize (params, 8192); Set the data flow length
HttpClient HttpClient = new Defaulthttpclient (httpparameters); //The parameter is passed in when constructing defaulthttpclient
The Getstatuscode () method gets the return status code with the status code for the HTTP request:
Success 2XX successfully processed the requested status code.
The server has successfully processed the request and provided the requested Web page.
The 204 server successfully processed the request, but did not return any content.
REDIRECT 3xx use redirects in each request no more than 5 times.
301 The requested page has been permanently moved to a new location. When URLs change, use 301 code. The new URL is saved in the Search engine index.
302 The requested Web page to a new location temporarily. The original URL is saved in the Search engine index.
304 If the page has not been updated since the requestor last requested it, use 304 code to tell the search engine robot that it saves bandwidth and overhead.
Client Error 4xx indicates a possible error in the request and prevents the server from processing.
the server does not understand the syntax of the request.
The 403 server rejected the request.
the 404 server could not find the requested Web page. Pages that do not exist on the server often return this code.
410 The requested resource is permanently deleted, the server returns this response. This code is similar to the 404 (not Found) code, but is sometimes used to replace the 404 code in cases where the resource existed before and now does not exist. If the resource has been permanently deleted, you should use 301 to specify a new location for the resource.
Server Error 5xx indicates that an internal error occurred while the server was processing the request. These errors may be the error of the server itself, not the request.
the server encountered an error and could not complete the request.
503
HttpClient Study Record