Use HttpURLConnection in Android to implement get POST JSON data and download pictures
Last Update:2016-01-04
Source: Internet
Author: User
<span id="Label3"></p><p><p><span style="font-size:18px;">Use HttpURLConnection in Android to implement get POST JSON data and download pictures<br></span></p></p><p><p><span style="font-size:18px;">Android6.0 all packages and classes of Apache HTTP client are marked as deprecated no longer recommended</span></p></p><p><p><span style="font-size:18px;">All http-related data request and commit operations are implemented through the HttpURLConnection class, and the reality is</span></p></p><p><p><span style="font-size:18px;">Many Android developers have been Apache HTTP client to do Andoird client and background HTTP interface number</span></p></p><p><p><span style="font-size:18px;">According to the interaction, I just used httpurlconnection to do an android app, accidentally stepped on a few</span></p></p><p><p><span style="font-size:18px;">The most common use of httpurlconnection to post JSON data with a GET request</span></p></p><p><p><span style="font-size:18px;">JSON Data. Also is the download picture, the download picture divides the display progress and does not show the progress two KINDS. Where submitted</span></p></p><p><p><span style="font-size:18px;">Data when involved in Chinese must first transcode the Chinese into utf-8 after the post submission, otherwise you will always encounter</span></p></p><p><p><span style="font-size:18px;"><span style="color:#ff0000;">HTTP</span> Error.</span></p></p><p><p><span style="font-size:18px;"></span></p></p><p><p><span style="font-size:18px;"><strong>one: example of GET request JSON data</strong></span></p></p><pre name="code" class="java">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 */ur Lconnection.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 ();/* 200 Represents HTTP OK */if (statusCode = =) {inputstream = new Bufferedinputstream (urlconnection.getinputstream ()); String response = httputil.convertinputstreamtostring (inputstream); Gson Gson = new Gson (); Userdto dto = Gson.fromjson (response, userdto.class);= null && dto.gettoken () = Null) {log.i ("token", "find the token =" + dto.gettoken ());} Return dto;}} Catch (Exception e) {e.printstacktrace ();} finally {if (inputstream! = Null) {try {inputstream.close ();} catch (ioexceptio n E) {e.printstacktrace ();}} If (urlconnection! = Null) {urlconnection.disconnect ();}} Return null;}</pre><span style="font-size:18px;"><span style="font-size:18px;"><strong>Second: Post submits JSON data</strong></span></span><p><p><span style="font-size:18px;"></span></p></p><pre name="code" class="java">Public map<string, string> Execute (notificationdto dto) {inputstream inputstream = null; HttpURLConnection urlconnection = null;try {url url = new URL (getUrl); urlconnection = (httpurlconnection) url.openconnect Ion ();/* 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);D ataoutputstream wr = new DataOutputStream ( Urlconnection.getoutputstream ()); Gson Gson = new Gson (); String jsonstring = Gson.tojson (dto); wr.writebytes (jsonstring); wr.flush (); wr.close ();//try to get Responseint 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;}</pre><p><p></p></p><p><p><span style="font-size:18px;"></span></p></p><p><p><span style="font-size:18px;"><strong>three: download Picture Show download Progress</strong></span></p></p><pre name="code" class="java">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) {message msg = new Message (); msg.obj = Result;handler.sendmessage (msg);} Protected Bitmap doinbackground (String ... geturls) {inputstream inputstream = null; HttpURLConnection urlconnection = null;try {//open connectionurl url = new URL (geturls[0]); urlconnection = (httpurlconnec Tion) 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; return bitmap;}} Catch (Exception e) {e.printstacktrace ();} finally {if (inputstream! = Null) {try {inputstream.close ();} catch (ioexceptio n E) {e.printstacktrace ();}} If (urlconnection! = Null) {urlconnection.disconnect ();}} Return null;}}</pre><span style="font-size:18px;"><span style="font-size:18px;"> <strong><span style="color:#ff0000;">summary:</span></strong> using HttpURLConnection to submit JSON data is encoded as UTF-8</span></span><p><p><span style="font-size:18px;">All Chinese characters must be pre-transcoded to UTF-8 and then the API corresponding to the backend server</span></p></p><p><p><span style="font-size:18px;">Decode to UTF-8, or it will error HTTP 400.</span></p></p><p><p>Use HttpURLConnection in Android to implement get POST JSON data and download pictures</p></p></span>