getUrlBytes(String)和getUrlString(String)
getUrlBytes(String)从指定URL获取原始数据并返回一个字节流数组。
getUrlString(String)将字节流数组转换成String
所以核心是getUrlBytes
下面给出代码实现:
public byte[] getUrlBytes(String urlSpec) throws IOException {
URL url = new URL(urlSpec);
HttpURLConnection connection = (HttpURLConnection) url.getContent();
try {
ByteArrayOutputStream out = new ByteArrayOutputStream();
InputStream in = connection.getInputStream();
//判断返回的输入流状态码是否为HTTP_OK(200)
if(connection.getResponseCode() != HttpURLConnection.HTTP_OK){
throw new IOException(connection.getResponseMessage() +
": with" +
urlSpec
);
}
int bytesRead = 0;
byte[] buffer = new byte[1024];
while((bytesRead = in.read(buffer)) > 0){
out.write(buffer, 0, bytesRead);
}
out.close();
return out.toByteArray();
} finally {
connection.disconnect();
}
}
public String getUrlString(String urlSpec) throws IOException {
return new String(getUrlBytes(urlSpec));
}