最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Android中使用HttpURLConnection實現(xiàn)GET POST JSON數(shù)據(jù)與下載圖片

 更新時間:2016年01月14日 11:16:25   作者:gloomyfish  
這篇文章主要介紹了Android中使用HttpURLConnection實現(xiàn)GET POST JSON數(shù)據(jù)與下載圖片,需要的朋友可以參考下

Android6.0中把Apache HTTP Client所有的包與類都標記為deprecated不再建議使用所有跟HTTP相關(guān)的數(shù)據(jù)請求與提交操作都通過HttpURLConnection類實現(xiàn),現(xiàn)實是很多Android開發(fā)者一直都Apache HTTP Client來做andoird客戶端與后臺HTTP接口數(shù)據(jù)交互,小編剛剛用HttpURLConnection做了一個android的APP,不小心踩到了幾個坑,總結(jié)下最常用的就通過HttpURLConnection來POST提交JSON數(shù)據(jù)與GET請求JSON數(shù)據(jù)。此外就是下載圖片,下載圖片分為顯示進度與不顯示進度兩種。其中提交數(shù)據(jù)的時候涉及中文一定要先把中文轉(zhuǎn)碼成utf-8之后在POST提交,否則就會一直遇到HTTP 400的錯誤。

一、GET請求JSON數(shù)據(jù)的例子

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數(shù)據(jù)

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 == 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 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 == 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; 
 } 
 
} 

總結(jié):使用HttpURLConnection提交JSON數(shù)據(jù)的時候編碼方式為UTF-8所有中文字符請一定要預(yù)先轉(zhuǎn)碼為UTF-8,然后在后臺服務(wù)器對應(yīng)的API中解碼為UTF-8,不然就會報錯HTTP 400。

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)Android軟件編程有所幫助。

相關(guān)文章

  • Android崩潰日志收集和保存解析

    Android崩潰日志收集和保存解析

    這篇文章主要為大家介紹了Android崩潰日志收集和保存解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2023-02-02
  • Android 圖片存儲到指定路徑和相冊的方法

    Android 圖片存儲到指定路徑和相冊的方法

    本篇文章主要介紹了Android 圖片存儲到指定路徑和相冊的方法,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2017-07-07
  • Android Fragment滑動組件ViewPager的實例詳解

    Android Fragment滑動組件ViewPager的實例詳解

    這篇文章主要介紹了Android Fragment滑動組件ViewPager的實例詳解的相關(guān)資料,需要的朋友可以參考下
    2017-05-05
  • 在Android中調(diào)用WebService實例

    在Android中調(diào)用WebService實例

    這篇文章主要介紹了在Android中調(diào)用WebService實例,有需要的朋友可以了解一下。
    2016-11-11
  • kotlin中使用ViewBinding綁定控件的方法

    kotlin中使用ViewBinding綁定控件的方法

    View Binding是Android Studio 3.6推出的新特性,主要用于減少findViewById的冗余代碼,但內(nèi)部實現(xiàn)還是通過使用findViewById,這篇文章主要介紹了kotlin中使用ViewBinding綁定控件,需要的朋友可以參考下
    2024-03-03
  • Android WebView無法彈出軟鍵盤的原因及解決辦法

    Android WebView無法彈出軟鍵盤的原因及解決辦法

    這篇文章主要介紹了Android WebView無法彈出軟鍵盤的原因及解決辦法的相關(guān)資料,非常不錯,具有參考借鑒價值,需要的朋友可以參考下
    2016-06-06
  • Android中通過MediaStore獲取音樂文件信息方法

    Android中通過MediaStore獲取音樂文件信息方法

    這篇文章主要介紹了Android中通過MediaStore獲取音樂文件信息方法,本文講解了獲取歌曲的名稱、歌曲的專輯名、歌曲的歌手名、歌曲文件的全路徑、歌曲文件的名稱、歌曲文件的發(fā)行日期等音樂文件信息的方法,需要的朋友可以參考下
    2015-04-04
  • Android Socket通信實現(xiàn)簡單聊天室

    Android Socket通信實現(xiàn)簡單聊天室

    這篇文章主要為大家詳細介紹了Android網(wǎng)絡(luò)編程之Socket通信實現(xiàn)簡單聊天室,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2018-03-03
  • Android應(yīng)用中加入微信分享簡單方法

    Android應(yīng)用中加入微信分享簡單方法

    這篇文章主要介紹了Android應(yīng)用中加入微信分享簡單方法,本文用簡潔明快的步驟講解了加入微信分享的方法,需要的朋友可以參考下
    2015-05-05
  • Android 8.0系統(tǒng)中應(yīng)用圖標的適配技巧

    Android 8.0系統(tǒng)中應(yīng)用圖標的適配技巧

    今天小編就為大家分享一篇關(guān)于Android 8.0系統(tǒng)中應(yīng)用圖標的適配技巧,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧
    2018-10-10

最新評論

太保市| 馆陶县| 罗定市| 两当县| 延安市| 石门县| 称多县| 曲阜市| 长垣县| 隆子县| 高平市| 颍上县| 奉新县| 浦北县| 丰台区| 霍邱县| 常熟市| 嵊泗县| 仪陇县| 广东省| 东源县| 深水埗区| 双峰县| 永德县| 广水市| 获嘉县| 义乌市| 靖江市| 南投市| 四会市| 如皋市| 府谷县| 潮安县| 永吉县| 达州市| 长治县| 灌阳县| 衡水市| 汝南县| 大兴区| 德州市|