国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁(yè) > 系統(tǒng) > Android > 正文

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

2020-04-11 10:59:12
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友

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

一、GET請(qǐng)求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; } 

三、下載圖片顯示下載進(jìn)度

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ù)的時(shí)候編碼方式為UTF-8所有中文字符請(qǐng)一定要預(yù)先轉(zhuǎn)碼為UTF-8,然后在后臺(tái)服務(wù)器對(duì)應(yīng)的API中解碼為UTF-8,不然就會(huì)報(bào)錯(cuò)HTTP 400。

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

發(fā)表評(píng)論 共有條評(píng)論
用戶(hù)名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 广宗县| 广州市| 巴南区| 宜宾县| 石屏县| 乌兰县| 桦南县| 科技| 青岛市| 建平县| 无棣县| 开鲁县| 惠来县| 台东县| 太原市| 长乐市| 日喀则市| 商河县| 连江县| 安义县| 金寨县| 峡江县| 扎鲁特旗| 尼木县| 腾冲县| 麻栗坡县| 施秉县| 津南区| 老河口市| 皋兰县| 阿城市| 鱼台县| 启东市| 彭山县| 阿拉尔市| 扎鲁特旗| 曲沃县| 保定市| 浦县| 林口县| 平定县|