android--Network Requests

Source: Internet
Author: User

1, the way to send HTTP requests on Android generally have two kinds, httpurlconnection and HttpClient;

2, the use of httpurlconnection:

1) Get HttpURLConnection instance: obtained by invoking the OpenConnection () method of the URL object;

2) The method used to set the HTTP request, there are two methods commonly used: GET and POST;

3) Other settings, such as setting the connection timeout, the number of milliseconds to read timeout;

Connection.setconnecttimeout (8000); Connection.setreadtimeout (8000);

4) Call HttpURLConnection's getInputStream () method to obtain the input stream returned by the server, through which the input stream can be read to the service-side data;

5) Finally, you need to call the disconnect () method to close the connection.

6) Sample code:

Privatestring Sendrequestwithhttpurlconnection () {string result=NULL; HttpURLConnection Connection=NULL; Try{URL URL=NewURL ("http://www.baidu.com"); Connection=(HttpURLConnection) url.openconnection (); Connection.setrequestmethod ("GET"); Connection.setconnecttimeout (8000); Connection.setreadtimeout (8000); InputStream InputStream=Connection.getinputstream (); BufferedReader BR=NewBufferedReader (NewInputStreamReader (InputStream)); StringBuilder SB=NewStringBuilder ();        String str;  while(str = br.readline ())! =NULL) {sb.append (str); } result=sb.tostring (); }Catch(Exception e) {e.printstacktrace (); }finally{        if(Connection! =NULL) {connection.disconnect (); }    }    returnresult;}

3, the use of HttpClient:

1) HttpClient is an interface that typically creates an instance of defaulthttpclient: HttpClient HttpClient = new Defaulthttpclient ();

2) Set the request:

--get Request: Create a HttpGet object and pass in the destination's network address, then call HttpClient's Execute () method;

--post Request: Create a HttpPost object and pass in the destination's network address, create a Namevaluepair collection to hold the arguments to be submitted, pass the parameter collection to a urlencodedformentity, and then call The HttpPost setentity () method passes the built-in urlencodedformentity into:

New Arraylist<namevaluepair>();p arams.add(new Basicnamevaluepair ("username", "admin")); Params.add(new basicnamevaluepair ("Password", "123456"new urlencodedformentity ( params, "Utf-8"); httppost.setentity (entity) ;

3) Call the Execute () method of HttpClient to initiate the request;

4) After executing the Execute () method, a HttpResponse is returned, and all the information returned by the Object server is included here, usually the status code returned by the server is removed, and if the 200 indicates that the request and response are successful, you can call GetEntity ( ) method to obtain a httpentity instance, and then use the static method of entityutils.tostring () to convert the httpentity to a string;

5) Sample code:

Privatestring Sendrequestwithhttpclient (string name, string pwd) {string result=NULL; HttpClient HttpClient=NULL; Try{httpClient=Newdefaulthttpclient (); HttpPost Post=NewHttpPost ("http://www.baidu.com"); List<NameValuePair> params =NewArraylist<namevaluepair>(); Params.add (NewBasicnamevaluepair ("name", name)); Params.add (NewBasicnamevaluepair ("pwd", PWD)); Urlencodedformentity Entity=NewUrlencodedformentity (params, "UTF-8");        Post.setentity (entity); HttpResponse Response=Httpclient.execute (POST); if(Response.getstatusline (). Getstatuscode () = = 200) {httpentity entity1=response.getentity (); Result= Entityutils.tostring (entity1, "UTF-8"); }    }Catch(Exception e) {e.printstacktrace (); }    returnresult;}

android--Network Requests

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.