Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 平台使用 HttpURLConnection 發送 POST 請求

編輯:關於 Android 程式設計

以下是一段在 Android 上以 POST 方式向伺服器發送請求、並處理 gzip 壓縮回應的實作。程式碼中的註解記錄了專案開發時實際踩到的問題,值得一併整理。

需要特別注意的是:在 Froyo(Android 2.2)之前的系統上,HttpURLConnection 的 HTTP 連線重用存在已知 bug,因此需要動手關閉 keep-alive 來避開。

/**

* HttpURLConnection post方式請求服務器

* @param urlpath

* @param requestData

* @return

* @throws IOException

*/

public static String requestByPost(String urlpath,String requestData) throws IOException{

// HTTP connection reuse which was buggy pre-froyo

//froyo之前的系統使用httpurlconnection存在bug

/*Workaround for bug pre-Froyo, see here for more info:

https://android-developers.blogspot.com/2011/09/androids-http-clients.html*/

if (Build.VERSION.SDK_INT < Build.VERSION_CODES.FROYO) {

System.setProperty("http.keepAlive", "false");

}

URL url = new URL(urlpath);

HttpURLConnection conn = (HttpURLConnection) url.openConnection();

conn.setDoInput(true);

conn.setConnectTimeout(TIMEOUT);

conn.setReadTimeout(TIMEOUT);

conn.setRequestMethod("POST");

conn.setDoOutput(true);

//需要設置 gzip的請求頭 才可以獲取Content-Encoding響應碼

conn.setRequestProperty("Accept-Encoding", "gzip, deflate");

conn.connect();

String urlEncodedRequestStr = URLEncoder.encode(requestData,"utf-8");

String requestStr = "jsonStr="+urlEncodedRequestStr;

conn.getOutputStream().write(requestStr.getBytes("utf-8"));

conn.getOutputStream().flush();

conn.getOutputStream().close();

String content_encode = conn.getContentEncoding();

System.out.println("content_encode:"+content_encode);

//如果是gzip的壓縮流 進行解壓縮處理

if(null!=content_encode&&!"".equals(content_encode)&&content_encode.equals("gzip")){

GZIPInputStream in = new GZIPInputStream(conn.getInputStream());

if(in == null){ return ""; }

ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();

int len ; byte [] buffer = new byte[1024];

while((len=in.read(buffer))!= -1){ arrayOutputStream.write(buffer, 0, len); }

in.close(); arrayOutputStream.close(); conn.disconnect();

str = new String(arrayOutputStream.toByteArray(),"utf-8");

//正常流處理

}else{

InputStream in = conn.getInputStream();

if(in == null){ return ""; }

ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();

int len ; byte [] buffer = new byte[1024];

while((len=in.read(buffer))!= -1){ arrayOutputStream.write(buffer, 0, len); }

in.close(); arrayOutputStream.close(); conn.disconnect();

str = new String(arrayOutputStream.toByteArray(),"utf-8");

}

return str;

}

這段程式碼的兩個重點:一是針對舊版本系統關閉 keep-alive 以避開連線重用的 bug;二是透過 Accept-Encoding 請求標頭搭配 GZIPInputStream 完成回應的解壓縮。記錄下來,算是替專案做個小小總結。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved