在web项目中,httpclient 工具被经常使用.最近一个需求是,俩个应用 ,
第一个应用存入用户上传图片地址,然后存储到ftp服务器上,
第二个应用使用httpclient读取第一个应用存入ftp的图片字节流.
下面是代码:
/**
* httpclient发送get请求
*/
public static byte[] httpGet(String uri) {
CloseableHttpClient httpclient = HttpClients.createDefault();
byte[] fileBytes = null;
try {
// 创建httpclient get请求.
HttpGet httpget = new HttpGet(uri);
System.out.println(" request for :" + httpget.getURI());
// 执行get请求.
CloseableHttpResponse response = httpclient.execute(httpget);
try {
//获取响应实体
HttpEntity entity = response.getEntity();
InputStream inputContent = entity.getContent();
fileBytes = input2byte(inputContent);
} finally {
response.close();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 关闭连接,释放资源
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return fileBytes;
}
/**
* inputStream转换为byte字节数组
* @param inStream
* @return
* @throws IOException
*/
public static final byte[] input2byte(InputStream inStream) throws IOException {
ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
byte[] buff = new byte[100];
int rc = 0;
while ((rc = inStream.read(buff, 0, 100)) > 0) {
swapStream.write(buff, 0, rc);
}
byte[] in2b = swapStream.toByteArray();
return in2b;
}
代码还不够完善.请多多指点.