获取并解析字节流的示例代码 java
- 一、获取字节流
- 需要下载并引用httpclient包,版本号在4.5以上。点此下载jar包
- public static byte[] getCode(String url)
byte[] arr=null;
HttpGet httpGet=new HttpGet(url);
CloseableHttpResponse response=null;
RequestConfig defaultRequestConfig=RequestConfig.custom().setSocketTimeout(60000).setConnectTimeout(60000).setConnectionRequestTimeout(60000).build();
try{
response=HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig).build().execute(httpGet);
if(response.getStatusLine().getStatusCode()==HttpStatus.SC_OK){
arr=EntityUtils.toByteArray(response.getEntity());
}
}catch(ClientProtocolException e1){
e1.printStackTrace();
}catch(IOException e1){
e1.printStackTrace();
}finally{
try{
if(null!=response)
response.close();
}catch(IOException e){
e.printStackTrace();
}
}
return arr;
}
- 二、解压方法
- public static byte[] uncompress(byte[] bytes) {
if (bytes == null || bytes.length == 0) {
return null;
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
ByteArrayInputStream in = new ByteArrayInputStream(bytes);
try {
GZIPInputStream ungzip = new GZIPInputStream(in);
byte[] buffer = new byte[256];
int n;
while ((n = ungzip.read(buffer)) >= 0) {
out.write(buffer, 0, n);
}
} catch (Exception e) {
e.printStackTrace();
}
return out.toByteArray();
}