Android中使用HttpURLConnection實現GET POST JSON資料與下載圖片

來源:互聯網
上載者:User

標籤:

Android中使用HttpURLConnection實現GET POST JSON資料與下載圖片

Android6.0中把Apache HTTP Client所有的包與類都標記為deprecated不再建議使用

所有跟HTTP相關的資料請求與提交操作都通過HttpURLConnection類實現,現實是

很多Android開發人員一直都Apache HTTP Client來做andoird用戶端與後台HTTP介面數

據互動,本人剛剛用HttpURLConnection做了一個android的APP,不小心踩到了幾個

坑,總結下最常用的就通過HttpURLConnection來POST提交JSON資料與GET請求

JSON資料。此外就是下載圖片,下載圖片分為顯示進度與不顯示進度兩種。其中提交

資料的時候涉及中文一定要先把中文轉碼成utf-8之後在POST提交,否則就會一直遇到

HTTP 400的錯誤。

一:GET請求JSON資料的例子

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;}
二:POST提交JSON資料

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 responseint statusCode = urlConnection.getResponseCode();if (statusCode == 200) {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", "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;}

三:下載圖片顯示下載進度

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 = (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;}}
總結:使用HttpURLConnection提交JSON資料的時候編碼方式為UTF-8

所有中文字元請一定要預先轉碼為UTF-8,然後在後台伺服器對應的API

中解碼為UTF-8,不然就會報錯HTTP 400。

Android中使用HttpURLConnection實現GET POST JSON資料與下載圖片

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.