Android (Java) network sends get/POST request parameter settings

Source: Internet
Author: User

Recently, I have made a project on Android Network Programming. Now I want to summarize the network connection methods in Android,

In Android, network communication is divided into socket programming and HTTP programming. Here we only introduce htt. The Network request method can be divided into GET request, post two request methods, get method in the data request, will attach the data to the URL after passing to the server, such as common: http://XXX.XXX.XXX/XX.aspx? Id = 1. The post method places the requested data in the HTTP request header and transmits it to the server as part of the request header.
Therefore, before HTTP programming, you must first determine which method is used for data requests.

There are two types of HTTP programming in Android: 1. httpurlconnection; 2. httpclient

First, we will introduce the GET request and POST request methods in httpurlconnection mode:

Private Map <string, string> paramsvalue; string urlpath = NULL; // sent from http: // 192.168.100.91: 8080/myweb/login? Username = ABC & Password = 123 public void initdata () {urlpath = "http: // 192.168.100.91: 8080/myweb/login"; paramsvalue = new hashmap <string, string> (); paramsvalue. put ("username", "111"); paramsvalue. put ("password", "222 ");}

GET request:

Private Boolean sendgetrequest (string path, Map <string, string> Params) throws exception {Boolean success = false; // stringbuilder is used to group the request address and parameter stringbuilder sb = new stringbuilder (); sb. append (PATH ). append ("? "); If (Params! = NULL & Params. Size ()! = 0) {for (map. entry <string, string> entry: Params. entryset () {// if the request parameters contain Chinese characters, urlencoder encoding GBK/utf8sb is required. append (entry. getkey ()). append ("= "). append (urlencoder. encode (entry. getvalue (), "UTF-8"); sb. append ("&");} sb. deletecharat (sb. length ()-1);} URL url = new URL (sb. tostring (); httpurlconnection conn = (httpurlconnection) URL. openconnection (); Conn. setconnecttimeout (20000); Conn. setrequestmethod ("get" ); If (conn. getresponsecode () = 200) {success = true;} If (Conn! = NULL) Conn. Disconnect (); Return success ;}

Postt method:

Private Boolean sendpostrequest (string path, Map <string, string> Params) throws exception {Boolean success = false; // stringbuilder is used to set the stringbuilder sb = new stringbuilder (); if (Params! = NULL & milliseconds Ms. Size ()! = 0) {for (map. entry <string, string> entry: Params. entryset () {sb. append (entry. getkey ()). append ("= "). append (urlencoder. encode (entry. getvalue (), "UTF-8"); sb. append ("&");} sb. deletecharat (sb. length ()-1 );} // entity is part of the Request body // if there is a Chinese character, it is encoded as username = % E4 % B8 % ad % E5 % 9B % BD & Password = 123 byte [] entity = sb. tostring (). getbytes (); Url url = new URL (PATH); httpurlconnection conn = (httpurlconnection) URL. openc Onnection (); Conn. setconnecttimeout (2000); // set Conn in post mode. setrequestmethod ("Post"); // The cache cannot be used for post requests. // urlconn. setusecaches (false); // to output data externally, set this conn. setdooutput (true); // configure the Content-Type of the connection and set it to application/X-WWW-form-urlencoded // set Content-Type to get the output stream, it is easy for the server to send messages. // For post requests, you must set Conn. setrequestproperty ("Content-Type", "application/X-WWW-form-urlencoded"); Conn. setrequestproperty ("Content-Length", entity. length + ""); // note the connection. getoutputstream implicitly performs connect. Outputstream out = Conn. getoutputstream (); // write the parameter value out. write (entity); // refresh and close out. flush (); out. close (); If (Conn. getresponsecode () = 200) {success = true;} If (Conn! = NULL) Conn. Disconnect (); Return success ;}

The httpclient method is simpler and easier to use than httpurlconnection. Let's take a look at the example:

GET request:

public String getRequest(String UrlPath,Map<String, String> params){String content=null;StringBuilder buf = new StringBuilder();if(params!=null &¶ms.size()!=0){            for (Map.Entry<String, String> entry : params.entrySet()) {            buf.append(entry.getKey()).append("=").append(URLEncoder.encode(entry.getValue(), "utf-8"));            buf.append("&");                                      }            buf.deleteCharAt(buf.length()-1);}content= buf.toString();HttpClient httpClient = new DefaultHttpClient();HttpGet getMethod = new HttpGet(content);HttpResponse response = null;try {response = httpClient.execute(getMethod);} catch (ClientProtocolException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}catch (Exception e) {e.printStackTrace();} if (response!=null&&response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { try {content = EntityUtils.toString(response.getEntity());} catch (ParseException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}} return content;}

Postt method:

Private Boolean sendpostrequesthttpclient (string path, Map <string, string> Params) throws exception {Boolean success = false; // encapsulate the request parameter list <namevaluepair> pair = new arraylist <namevaluepair> (); If (Params! = NULL &&! Params. isempty () {for (map. entry <string, string> entry: Params. entryset () {pair. add (New basicnamevaluepair (entry. getkey (), entry. getvalue () ;}}// change the request parameter to the urlencodedformentity UEE = new urlencodedformentity (pair, "UTF-8") part of the Request body "); // use the httppost object to set the URL path httppost post = new httppost (PATH); // send the request body post. setentity (UEE); // create a browser object to send the post object to the server and return the Response Message defaulthttpclient dHC = new defaulthttpclient (); httpresponse response = dhc.exe cute (post); If (response. getstatusline (). getstatuscode () = 200) {success = true;} return success ;}

Android Network interaction is still very important, and it is worth studying. OK, so I will write it here first.

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.