背景:
本例中使用HttpClient Get请求下载存储系统中的文件。根据存储系统提供的接口文档需要传入参数。
实例1(使用字符串直接拼接get请求中的参数)
1.参数:
filename:存储系统上存储的唯一文件名。(文件名一般是文件上传时生成一个唯一的文件夹路径,这个路径保存在数据库中,要下载文件时,数据库中取出文件夹路径名,去存储系统上下载)
2.返回值
输入流,以流的形式返回,不需要保存在本地浪费资源,使用时调用方法传参拿到返回值就可以使用
eg:
public static InputStream doGet(String filename) {
//创建HttpClient实例
CloseableHttpClient httpClient = HttpClients.createDefault();
StringBuffer stringBuffer = new StringBuffer();
//拼接get请求URL(url一般包含接口需要的用户名,密码,文件名等参数)
String url = stringBuffer.append(EmailGradeTask.EMAILGRADETASKDOWNLOADURL).append(filename).toString();
InputStream inputStream = null;
try {
//创建get方法连接实例,在get方法中传入待连接地址
HttpGet httpGet = new HttpGet(url);
//发起请求,并返回请求响应
HttpResponse httpResponse = httpClient.execute(httpGet);
//得到响应实体
HttpEntity entity = httpResponse.getEntity();
//得到实体中文件
inputStream = entity.getContent();
long length = entity.getContentLength();
if (length <= 0) {
System.out.println("下载文件不存在!");
return inputStream;
}
System.out.println("The response value of token:" + httpResponse.getFirstHeader("token"));
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
// try {
// if (inputStream != null) {
// inputStream.close();
// }
// } catch (IOException e) {
// e.printStackTrace();
// }
}
return inputStream;
}
实例二(有的get请求直接拼接请求参数访问不到资源,需要用到URI包封装参数)
public static String httpClientBySina() throws Exception{
// 创建Httpclient对象
CloseableHttpClient httpclient = HttpClients.createDefault();
// 定义请求的参数
URI uri = new URIBuilder("https://hq.sinajs.cn/").setParameter("rn", "1563526094204").setParameter("list", "USDCNY").build();
// 创建http GET请求
HttpGet httpGet = new HttpGet(uri);
//response 对象
CloseableHttpResponse response = null;
String resultString="0";
try {
// 执行http get请求
response = httpclient.execute(httpGet);
// 判断返回状态是否为200
if (response.getStatusLine().getStatusCode() == 200) {
resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
// System.out.println("内容长度:" + resultString);
} else {
throw new Exception("新浪接口获取汇率失败!");
}
} finally {
if (response != null) {
response.close();
}
httpclient.close();
}
return resultString;
}