日期:2014-05-20 浏览次数:20784 次
public static void main(String[] args) throws Exception {
String result = "";
URL url = new URL("http://h.vimage4.com/upload/actpics/pingou/2013/11m/14/kaizi/sh.js");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(7 * 1000);
if (conn.getResponseCode() != 200)
throw new RuntimeException("请求url失败");
InputStream is = conn.getInputStream();
if ("gzip".equals(conn.getContentEncoding())) {
result = readDataForZgip(is, "utf-8");
}
conn.disconnect();
System.err.println("ContentEncoding: " + conn.getContentEncoding());
System.out.println(result);
}
public static String readDataForZgip(InputStream inStream,
String charsetName) throws Exception {
GZIPInputStream gzipStream = new GZIPInputStream(inStream);
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = -1;
while ((len = gzipStream.read(buffer)) != -1) {
outStream.write(buffer, 0, len);
}
byte[] data = outStream.toByteArray();
outStream.close();
gzipStream.close();
inStream.close();
return new String(data, charsetName);
}