Several kinds of network request way in Android development detailed _android

Source: Internet
Author: User

Android apps often interact with the server side, which requires the mobile client to send a network request, and here are four common network requests, and I've done this through the Android unit test to complete these four methods. It's not clear how the Android unit test students look at the Android unit test steps in the Android Development tips summary.

The HttpURLConnection class in the java.net package

Get Way:

Get mode request public 
static void Requestbyget () throws Exception { 
 String path = ' Http://www.jb51.net/logins.jsp?id =helloworld&pwd=android "; 
 Creates a new URL object 
 URL url = new URL (path); 
 Open a httpurlconnection connection 
 httpurlconnection urlconn = (httpurlconnection) url.openconnection (); 
 Set the connection Timeout 
 urlconn.setconnecttimeout (5 * 1000); 
 Start connecting 
 urlconn.connect (); 
 To determine if the request succeeded 
 if (urlconn.getresponsecode () = = http_200) { 
  //Get the returned data 
  byte[]/Readstream ( Urlconn.getinputstream ()); 
  LOG.I (Tag_get, "Get mode request succeeded, return data as follows:"); 
  LOG.I (Tag_get, new String (data, "UTF-8")); 
 } else { 
  log.i (tag_get, "Get mode request Failed"); 
 } 
 Close connection 
 urlconn.disconnect (); 

Post method:

Post mode requests public static void Requestbypost () throws Throwable {String path = "http://www.jb51.net/logins.jsp"; The requested parameter is converted to a byte array String params = "id=" + urlencoder.encode ("HelloWorld", "UTF-8") + "&pwd=" + Urlencoder.encode 
 ("Android", "UTF-8"); 
 byte[] PostData = Params.getbytes (); 
 Creates a new URL object url url = new URL (path); 
 Open a httpurlconnection connection httpurlconnection urlconn = (httpurlconnection) url.openconnection (); 
 Set the connection timeout Urlconn.setconnecttimeout (5 * 1000); 
 The POST request must set the Allow output urlconn.setdooutput (true); 
 The POST request cannot use the cache Urlconn.setusecaches (false); 
 Set to POST request Urlconn.setrequestmethod ("post"); 
 Urlconn.setinstancefollowredirects (TRUE); 
 Configuration Request Content-type Urlconn.setrequestproperty ("Content-type", "Application/x-www-form-urlencode"); 
 Start connecting Urlconn.connect (); 
 Send request parameter DataOutputStream dos = new DataOutputStream (Urlconn.getoutputstream ()); 
 Dos.write (PostData); 
 Dos.flush (); 
 Dos.close (); Determine if the request succeeded if (urlconn.geTresponsecode () = = http_200) {//Get the returned data byte[]/Readstream (Urlconn.getinputstream ()); 
  LOG.I (Tag_post, "POST request method successful, return data as follows:"); 
 LOG.I (Tag_post, new String (data, "UTF-8")); 
 else {log.i (tag_post, "POST mode request Failed"); 
 
 } 
}

HttpGet and HttpPost classes in Org.apache.http packages

Get Way:

HttpGet mode request public 
static void Requestbyhttpget () throws Exception { 
 String path = "http://www.jb51.net/ Logins.jsp?id=helloworld&pwd=android "; 
 New HttpGet Object 
 httpget httpget = new HttpGet (path); 
 Gets the HttpClient object 
 httpclient httpclient = new Defaulthttpclient (); 
 Get HttpResponse instance 
 httpresponse httpresp = Httpclient.execute (httpget); 
 Judgment is enough to request success 
 if (Httpresp.getstatusline (). Getstatuscode () = = http_200) { 
  //Get returned data 
  String result = Entityutils.tostring (Httpresp.getentity (), "UTF-8"); 
  LOG.I (Tag_httpget, "HttpGet the way the request succeeds, returns the data as follows:"); 
  LOG.I (tag_httpget, result); 
 } else { 
  log.i (tag_httpget, HttpGet mode request failed); 
 } 

Post method:

//HttpPost mode request public static void Requestbyhttppost () throws Exception {String path 
 = "http://www.jb51.net/"; 
 New HttpPost object HttpPost httppost = new HttpPost (path); 
 Post parameter list<namevaluepair> params = new arraylist<namevaluepair> (); 
 Params.add (New Basicnamevaluepair ("id", "HelloWorld")); 
 Params.add (New Basicnamevaluepair ("pwd", "Android")); Set the character set httpentity entity = new Urlencodedformentity (params, HTTP. 
 UTF_8); 
 Set parameter entity httppost.setentity (entity); 
 Gets the HttpClient object httpclient httpclient = new Defaulthttpclient (); 
 Get HttpResponse instance HttpResponse Httpresp = Httpclient.execute (HttpPost); Judgment is enough to request success if (Httpresp.getstatusline (). Getstatuscode () = = http_200) {//Get returned data String result = Entityutils.tos 
  Tring (Httpresp.getentity (), "UTF-8"); 
  LOG.I (Tag_httpget, "HttpPost the way the request succeeds, returns the data as follows:"); 
 LOG.I (tag_httpget, result); 
 else {log.i (Tag_httpget, "HttpPost method request Failed"); } 
} 

These are some of the code, testing in the test class to run the corresponding test methods can be. Complete code point download here: Source download

Thank you for reading, I hope to help you, thank you for your support for this site!

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.