[Android-010] [use HttpClient]
HttpClientSend get requestCreate a client object
HttpClient client = new DefaultHttpClient();
Create a get request object
HttpGet hg = new HttpGet(path);
Send a get request, establish a connection, and return the response header object.
HttpResponse hr = hc.execute(hg);
Gets the status row object and obtains the status code. If the value is 200, the request is successful.
If (hr. getStatusLine (). getStatusCode () = 200) {// get the input stream InputStream returned by the server = hr. getEntity (). getContent (); String text = Utils. getTextFromStream (is );}
Send post request
// Create a client object HttpClient client = new DefaultHttpClient (); // create a post request object HttpPost hp = new HttpPost (path );
Put the data to be submitted to the server in the post object
// The data to be submitted is saved as a key-value pair in the List object of BasicNameValuePair
Parameters = new ArrayList
(); BasicNameValuePair bnvp = new BasicNameValuePair (name, name); BasicNameValuePair bnvp2 = new BasicNameValuePair (pass, pass); parameters. add (bnvp); parameters. add (bnvp2); // create an object and specify the URL encoding code table UrlEncodedFormEntity entity = new UrlEncodedFormEntity (parameters, UTF-8); // set the object hp for the post request. setEntity (entity );
Asynchronous HttpClient framework
Send get request
// Create an asynchronous httpclient object AsyncHttpClient ahc = new AsyncHttpClient (); // send the get request ahc. get (path, new MyHandler ());
Note the time when the AsyncHttpResponseHandler method is called.
Class MyHandler extends AsyncHttpResponseHandler {// The http request is successful and the return code is 200. The system calls back this method @ Override public void onSuccess (int statusCode, Header [] headers, // The content of responseBody is the Data byte [] responseBody) {Toast. makeText (MainActivity. this, new String (responseBody), 0 ). show () ;}// http request failed. The return code is not 200. The system calls back this method @ Override public void onFailure (int statusCode, Header [] headers, byte [] responseBody, throwable error) {Toast. makeText (MainActivity. this, the return code is not 200, 0 ). show ();}}
Send a post request using the RequestParams object to encapsulate the data to be carried
// Create an asynchronous httpclient object AsyncHttpClient ahc = new AsyncHttpClient (); // create RequestParams to encapsulate the data to be carried in RequestParams rp = new RequestParams (); rp. add (name, name); rp. add (pass, pass); // send the post request ahc. post (path, rp, new MyHandler ());