android http gzip,Android平台下使用HttpUrlConnection gzip post

public static String requestByPost(String urlpath,String

requestData) throws IOException{

// HTTP connection reuse which was buggy pre-froyo

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

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;

}

添加的注释是项目中实际遇到的问题,记下来小小总结下!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值