GET and POST requests of the HttpUrlConnection class of Android,

Source: Internet
Author: User

GET and POST requests of the HttpUrlConnection class of Android,

1/** 2 * get method use 3 */4 private void httpGet () {5 new Thread () {6 @ Override 7 public void run (){
// Here, LOGIN is the spliced parameter 8 String path = LOGIN + "? Phone = 12345678900 & password = 123456 "; 9 URL url; 10 HttpURLConnection connection; 11 try {12 url = new URL (path); 13 connection = (HttpURLConnection) url. openConnection (); 14 connection. setConnectTimeout (4000); // sets the connection timeout of 15 connections. setRequestMethod ("GET"); // sets the Request Method 16 17 connection. setRequestProperty ("Content-Type", "application/x-www-form-urlencoded"); // sets the Content of the request body, the same is true by default everywhere, indicating that the requested text content is 18 19 int responseCode = connection. getResponseCode (); 20 if (responseCode = HttpURLConnection. HTTP_ OK) {21 InputStream inputStream = connection. getInputStream (); 22 final String s = stremToString (inputStream); 23 24 runOnUiThread (new Runnable () {25 @ Override26 public void run () {27 Toast. makeText (MainActivity. this, s, Toast. LENGTH_SHORT ). show (); 28} 29}); 30 inputStream. close (); 31} 32 33} catch (Exception e) {34 e. printStackTrace (); 35} 36} 37 }. start (); 38}
1/** 2 * post method 3 */4 private void httpPost (final Map <String, String> prams) {5 new Thread () {6 @ Override 7 public void run () {8 if (prams = null) {9 runOnUiThread (new Runnable () {10 @ Override11 public void run () {12 Toast. makeText (MainActivity. this, "parameter missing! ", Toast. LENGTH_SHORT ). show (); 13} 14}); 15 return; 16} 17 URL; 18 HttpURLConnection connection; 19 try {20 // concatenate the input request parameter 21 StringBuffer buffer = new StringBuffer (); 22 // read the parameter 23 for (map. entry <String, String> entry: prams. entrySet () {24 String key = entry. getKey (); 25 String value = entry. getValue (); 26 // The concatenation parameter, for example, phone = 12345678900 & password = 12345627 buffer. append (key + "=" + URLEncoder. e Ncode (value, "UTF-8") + "&"); 28} 29 // delete the end of the Splicing & Symbol 30 buffer. deleteCharAt (buffer. length ()-1); 31 // REGISTER is a test request address of my own server 32 url = new URL (REGISTER); 33 connection = (HttpURLConnection) url. openConnection (); 34 connection. setConnectTimeout (4000); 35 36 // The output stream here indicates the server's response to the Customer Service. The output stream is InPutStream37 // The input stream here indicates that the client inputs data to the server, that is, OutPutStream38 connection. setDoInput (true); // get the server response output stream. The default value is true. 39 conne is not required. Ction. setDoOutput (true); // you can write data to the service to obtain the input stream from the server. 40 connection. setRequestMethod ("POST"); 41 // The content requested to the server is set here. The text content is the 42 connection that can be set by default. setRequestProperty ("Content-Type", "application/x-www-form-urlencoded"); 43 // set the length of the Request body to 44 connections. setRequestProperty ("Content-Length", String. valueOf (buffer. toString (). getBytes (). length); 45 // write the Request body 46 connection to the server. getOutputStream (). write (buffer. toString (). getBytes (); 47 // get the Request status? HttpURLConnection. HTTP_ OK is the 48 int responseCode = connection. getResponseCode (); 49 if (responseCode = HttpURLConnection. HTTP_ OK) {50 InputStream inputStream = connection. getInputStream (); 51 final String result = stremToString (inputStream); 52 runOnUiThread (new Runnable () {53 @ Override54 public void run () {55 Toast. makeText (MainActivity. this, result, Toast. LENGTH_SHORT ). show (); 56} 57}); 58 inputStream. close (); 59} 60 61} catch (Exception e) {62 e. printStackTrace (); 63} 64} 65 }. start (); 66}
1/** 2 * convert the input stream to a String of 3*4 * @ param inputStream 5 * @ return 6 * @ throws IOException 7 */8 private String stremToString (InputStream inputStream) throws IOException {9 ByteArrayOutputStream bos = new ByteArrayOutputStream (); 10 if (inputStream! = Null) {11 int len; 12 byte [] bytes = new byte [1024]; 13 while (len = inputStream. read (bytes ))! =-1) {14 bos. write (bytes, 0, len); 15} 16 return bos. toString (); 17} else {18 return ""; 19} 20}

Finally, if you do not understand or are not clear about it, you can leave a message to me. Welcome to give me suggestions or point out problems. We need a learning process for each other.

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.