其中有一个原因是由于gzip导致的。
public class CTest1 {
public static void main(String[] args) throws Exception {
System.out.println(doGet());
}
/**
* Get Request
* 网络数据
* @return
* @throws Exception
*/
public static String doGet() throws Exception {
URL localURL = new URL("http://www.bilibili.com/index/ding.json");
URLConnection connection = localURL.openConnection();
HttpURLConnection httpURLConnection = (HttpURLConnection) connection;
httpURLConnection.setRequestProperty("Accept-Charset", "utf-8");
httpURLConnection.setUseCaches(false); //设置缓存
httpURLConnection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
httpURLConnection.setRequestProperty("Accept-Encoding", "gzip,deflate");
InputStream inputStream = null;
InputStreamReader inputStreamReader = null;
BufferedReader reader = null;
StringBuffer resultBuffer = new StringBuffer();
String tempLine = null;
if (httpURLConnection.getResponseCode() >= 300) {
throw new Exception(
"HTTP Request is not success, Response code is "
+ httpURLConnection.getResponseCode());
}
try {
System.out.println(httpURLConnection.getContentEncoding());
inputStream = httpURLConnection.getInputStream();
InputStream urlStream = new GZIPInputStream(inputStream);
inputStreamReader = new InputStreamReader(urlStream, "utf-8");
reader = new BufferedReader(inputStreamReader);
while ((tempLine = reader.readLine()) != null) {
resultBuffer.append(tempLine);
}
} finally {
if (reader != null) {
reader.close();
}
if (inputStreamReader != null) {
inputStreamReader.close();
}
if (inputStream != null) {
inputStream.close();
}
}
return resultBuffer.toString();
}
}