Android平台下使用HttpUrlConnection

來源:互聯網
上載者:User

/**
* 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:
               http://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();
// //擷取所有回應標頭欄位
//    Map< String,List< String>> map = conn.getHeaderFields();
//    //遍曆所有的回應標頭欄位
//    if(null!=map){
//      for (String key : map.keySet()){
//      System.out.println(key + "--->" + map.get(key));
//      }
//    }
String content_encode = conn.getContentEncoding();
System.out.println("content_encode:"+content_encode);
// int responseCode = conn.getResponseCode();
// System.out.println("responseCode:"+responseCode);
// if(responseCode != 200){
// String message = conn.getResponseMessage();
// throw new IOException("ResponseCode:"+responseCode+",Message:"+message);
// }

//如果是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;
}

添加的注釋是項目中實際遇到的問題,記下來小小總結下!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.