Android uses HttpURLConnection to implement get POST JSON data with download picture _android

Source: Internet
Author: User

Android6.0 the Apache HTTP client all the packages and classes are marked as deprecated no longer recommends that all HTTP-related data requests and submissions be implemented through the HttpURLConnection class, The reality is that a lot of Android developers have always been Apache HTTP clients to do Andoird client and back-end HTTP Interface data interaction, small series just used httpurlconnection to do an Android app, Accidentally stepped on a few pits, summed up the most commonly used on the httpurlconnection to post the JSON data and GET request JSON data . In addition to downloading pictures, download the picture is divided into show progress and not show progress two kinds. When the data is submitted, the Chinese must first turn the Chinese code into utf-8 after the post, or you will always encounter HTTP 400 error.

One, GET request JSON data example

Public userdto Execute (String ... params) {InputStream inputstream = null; 
 
 HttpURLConnection urlconnection = null; 
  try {//read Responseurlencoder.encode (para, "GBK"); String urlwithparams = domain_address + Member_request_token_url + "? Username=" + Java.net.URLEncoder.encode (params[0), 
  "Utf-8") + "&password=" + params[1]; 
  URL url = new URL (urlwithparams); 
 
  URLConnection = (httpurlconnection) url.openconnection (); /* Optional Request Header * * Urlconnection.setrequestproperty ("Content-type", "Application/json; 
 
  Charset=utf-8 "); 
 
  /* Optional Request Header * * Urlconnection.setrequestproperty ("Accept", "Application/json"); 
  /* for GET request */Urlconnection.setrequestmethod ("get"); 
 
  int statusCode = Urlconnection.getresponsecode (); /* Represents HTTP OK */if (StatusCode = =) {InputStream = new Bufferedinputstream (urlconnection.getinputs 
   Tream ()); 
 String response = httputil.convertinputstreamtostring (InputStream);  Gson Gson = new Gson (); 
   Userdto DTO = Gson.fromjson (response, Userdto.class); 
   if (dto!= null && dto.gettoken ()!= null) {LOG.I ("token", "find the token =" + Dto.gettoken ()); 
  return to DTO; 
 } catch (Exception e) {e.printstacktrace (); 
   finally {if (InputStream!= null) {try {inputstream.close (); 
   catch (IOException e) {e.printstacktrace (); 
  } if (URLConnection!= null) {urlconnection.disconnect (); 
} return null; 
 }

Two, post-submit JSON data

Public map<string, string> execute (notificationdto dto) {InputStream inputstream = null; 
 HttpURLConnection urlconnection = null; 
  try {URL url = new URL (getUrl); 
 
  URLConnection = (httpurlconnection) url.openconnection (); /* Optional Request Header * * Urlconnection.setrequestproperty ("Content-type", "Application/json; 
 
  Charset=utf-8 "); 
  /* Optional Request Header * * Urlconnection.setrequestproperty ("Accept", "Application/json"); 
   
  Dto.setcreator (Java.net.URLEncoder.encode (Dto.getcreator (), "Utf-8")); 
  Read Response/* for GET request */Urlconnection.setrequestmethod ("POST"); 
  Urlconnection.setdooutput (TRUE); 
  DataOutputStream WR = new DataOutputStream (Urlconnection.getoutputstream ()); 
  Gson Gson = new Gson (); 
  String jsonstring = Gson.tojson (DTO); 
  Wr.writebytes (jsonstring); 
  Wr.flush (); 
  Wr.close (); 
  Try to get response int statusCode = Urlconnection.getresponsecode (); if (StatusCode = =) {InputStream =New Bufferedinputstream (Urlconnection.getinputstream ()); 
   String response = httputil.convertinputstreamtostring (InputStream); 
   map<string, string> resultmap = Gson.fromjson (response, Map.class); 
   if (resultmap!= null && resultmap.size () > 0) {log.i ("Applydesigner", "Check the map with key"); 
  return resultmap; 
 } catch (Exception e) {e.printstacktrace (); 
   finally {if (InputStream!= null) {try {inputstream.close (); 
   catch (IOException e) {e.printstacktrace (); 
  } if (URLConnection!= null) {urlconnection.disconnect (); 
} return null; 
 }

third, download pictures show download Progress

Package Com.example.demo; 
Import Java.io.ByteArrayInputStream; 
Import Java.io.ByteArrayOutputStream; 
Import java.io.IOException; 
Import Java.io.InputStream; 
Import java.net.HttpURLConnection; 
 
Import Java.net.URL; 
Import Android.graphics.Bitmap; 
Import Android.graphics.BitmapFactory; 
Import Android.os.AsyncTask; 
Import Android.os.Handler; 
Import Android.os.Message; 
 
Import Android.util.Log; 
 
 public class Imageloadtask extends Asynctask<string, Void, bitmap> {private Handler Handler; 
 Public Imageloadtask (Handler Handler) {this.handler = Handler; 
  } protected void OnPostExecute (Bitmap result) {msg = new message (); 
  Msg.obj = result; 
 Handler.sendmessage (msg); 
  } protected Bitmap Doinbackground (String ... geturls) {inputstream = null; 
 
  HttpURLConnection urlconnection = null; 
   try {//open connection URL url = new URL (geturls[0]); 
   URLConnection = (httpurlconnection) url.openconnection (); /* FOR GET Request */Urlconnection.setrequestmethod ("get"); 
   int filelength = Urlconnection.getcontentlength (); 
   int statusCode = Urlconnection.getresponsecode (); 
    if (StatusCode = =) {InputStream = Urlconnection.getinputstream (); 
    byte data[] = new byte[4096]; 
    Long total = 0; 
    int count; 
    Bytearrayoutputstream output = new Bytearrayoutputstream (); 
     while (count = inputstream.read (data))!=-1} {total = count; Publishing the progress ... if (filelength > 0 && handler!= null) {Handler.sendemptymessage ( (int) (total * 100/filelength)) 
     -1); 
    } output.write (data, 0, count); 
    } bytearrayinputstream bufferinput = new Bytearrayinputstream (Output.tobytearray ()); 
    Bitmap Bitmap = Bitmapfactory.decodestream (bufferinput); 
    Inputstream.close (); 
    Bufferinput.close (); 
    Output.close (); 
    LOG.I ("image", "already get the image by UUID:" + geturls[0]); Handler.sendemptymessAge (100); 
   return bitmap; 
  } catch (Exception e) {e.printstacktrace (); 
    finally {if (InputStream!= null) {try {inputstream.close (); 
    catch (IOException e) {e.printstacktrace (); 
   } if (URLConnection!= null) {urlconnection.disconnect (); 
 } return null; 
 } 
 
}

Summary: Use HttpURLConnection to submit JSON data when the encoding is UTF-8 all Chinese characters please be sure to advance the code to UTF-8, and then in the background server corresponding to the API decoding to UTF-8, otherwise it will error HTTP 400.

The above is the entire content of this article, I hope to learn more about Android software programming help.

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.