How to Use HttpURLConnection in Android to implement get post json data and download images
Use HttpURLConnection in Android to implement get post json data and download images
All Apache HTTP Client packages and classes are marked as deprecated in Android6.0.
All HTTP-related data request and submission operations are implemented through the HttpURLConnection class. The reality is that
Many Android Developers always use Apache HTTP Client as the andoird Client and the number of backend HTTP Interfaces
According to the interaction, I just used HttpURLConnection as an android APP, accidentally stepping on several
In summary, the most common method is to use HttpURLConnection to post json data and GET requests.
JSON data. In addition, you can download images in two ways: display progress and no display progress. Submit
When data involves Chinese characters, you must first transcode Chinese to UTF-8 and then submit the data in POST. Otherwise, you will always encounter
HTTP 400 error.
I. Example of GET request JSON data
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();/* 200 represents HTTP OK */if (statusCode == 200) {inputStream = new BufferedInputStream(urlConnection.getInputStream());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 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;}
Ii. Submit JSON data using POST
public Map
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 responseint statusCode = urlConnection.getResponseCode();if (statusCode == 200) {inputStream = new BufferedInputStream(urlConnection.getInputStream());String response = HttpUtil.convertInputStreamToString(inputStream);Map
resultMap = gson.fromJson(response, Map.class);if (resultMap != null && resultMap.size() > 0) {Log.i("applyDesigner", "please 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;}
Iii. Show the 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
{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 = (HttpURLConnection) url.openConnection();/* for Get request */urlConnection.setRequestMethod("GET");int fileLength = urlConnection.getContentLength();int statusCode = urlConnection.getResponseCode();if (statusCode == 200) {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:The encoding method for submitting JSON data using HttpURLConnection is UTF-8
All Chinese characters must be pre-transcoded as UTF-8, and then in the background server corresponding API
Or the HTTP 400 error will be reported.