Java | 使用HttpClient发送网络请求
使用HttpClient发送get或post请求,访问网络资源。
一、添加maven依赖
在解析数据时往往会配合json使用,所以同时添加fastjson依赖。
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.2</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.56</version>
</dependency>
二、使用方法
1. 发送get请求
- 请求方法
public static void get(String url) throws IOException {
//请求参数设置
RequestConfig requestConfig = RequestConfig.custom()
//读取目标服务器数据超时时间
.setSocketTimeout(10000)
//连接目标服务器超时时间
.setConnectTimeout(10000)
//从连接池获取连接的超时时间
.setConnectionRequestTimeout(10000)
.build();
CloseableHttpClient httpClient = null;
HttpGet request = null;
CloseableHttpResponse response = null;
try {
//创建HttpClient
httpClient = HttpClients.createDefault();
//使用url构建get请求
request = new HttpGet(url);
//填充请求设置
request.setConfig(requestConfig);
//发送请求,得到响应
response = httpClient.execute(request);
//获取响应状态码
int statusCode = response.getStatusLine().getStatusCode();
//状态码200 正常
if (statusCode == 200) {
//解析响应数据
HttpEntity entity = response.getEntity();
//字符串格式数据
String string = EntityUtils.toString(entity, "UTF-8");
System.out.println("字符串格式:" + string);
//json格式数据
JSONObject jsonObject = JSONObject.parseObject(string);
System.out.println("json格式:" + jsonObject);
} else {
throw new HttpResponseException(statusCode, "响应异常");
}
} finally {
if (response != null) {
response.close();
}
if (request != null) {
request.releaseConnection();
}
if (httpClient != null) {
httpClient.close();
}
}
}
- 模拟接口
@GetMapping("/getJsonData2")
public JSONObject getJson2(String name, int age) {
JSONObject jsonObject = new JSONObject();
jsonObject.put("name", name);
jsonObject.put("age", age);
return jsonObject;
}
- 测试
使用 ?key1=value1&key2=value2 的形式传入参数
public static void main(String[] args) {
String url = "http://localhost:8088/getJsonData2?name=jack&age=18";
try {
get(url);
} catch (IOException e) {
e.printStackTrace();
}
}
- 结果
2. 发送post请求
- 请求方法
public static void post(String url, Object param) throws Exception {
//请求参数设置
RequestConfig requestConfig = RequestConfig.custom()
//读取目标服务器数据超时时间
.setSocketTimeout(10000)
//连接目标服务器超时时间
.setConnectTimeout(10000)
//从连接池获取连接的超时时间
.setConnectionRequestTimeout(10000)
.build();
CloseableHttpClient httpClient = null;
HttpPost request = null;
CloseableHttpResponse response = null;
try {
//创建HttpClient
httpClient = HttpClients.createDefault();
//使用url构建post请求
request = new HttpPost(url);
//填充请求设置
request.setConfig(requestConfig);
//判断参数类型 可为Map或JSONObject
if (null != param) {
String type = param.getClass().toString();
if (type.contains("JSON")) {
StringEntity entity = new StringEntity(param.toString(), "UTF-8");
entity.setContentEncoding("UTF-8");
entity.setContentType("application/json");
request.setEntity(entity);
} else if (type.contains("Map")) {
Map<String, Object> map = (Map) param;
List<NameValuePair> pairs = new ArrayList<>();
for (Map.Entry<String, Object> entry : map.entrySet()) {
pairs.add(new BasicNameValuePair(entry.getKey(), String.valueOf(entry.getValue())));
}
UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(pairs, "UTF-8");
urlEncodedFormEntity.setContentType("application/x-www-form-urlencoded");
request.setEntity(urlEncodedFormEntity);
} else {
throw new Exception("不支持的参数类型");
}
response = httpClient.execute(request);
//获取响应状态码
int statusCode = response.getStatusLine().getStatusCode();
//状态码200 正常
if (statusCode == 200) {
//解析响应数据
HttpEntity entity = response.getEntity();
//字符串格式数据
String string = EntityUtils.toString(entity, "UTF-8");
System.out.println("字符串格式:" + string);
//json格式数据
JSONObject jsonObject = JSONObject.parseObject(string);
System.out.println("json格式:" + jsonObject);
} else {
throw new HttpResponseException(statusCode, "响应异常");
}
}
} finally {
if (response != null) {
response.close();
}
if (request != null) {
request.releaseConnection();
}
if (httpClient != null) {
httpClient.close();
}
}
}
- 模拟接口
@PostMapping("/postData")
public JSONObject postData(@RequestBody JSONObject jsonObject) {
jsonObject.put("time", System.currentTimeMillis());
return jsonObject;
}
- 测试
public static void main(String[] args) {
String url = "http://localhost:8088/postData";
JSONObject param = new JSONObject();
param.put("name", "chen");
try {
post(url, param);
} catch (Exception e) {
e.printStackTrace();
}
}
- 结果
3. 下载文件
- 请求方法
public static void downloadFile(String url, String savePath, String filename) throws IOException {
//请求参数设置
RequestConfig requestConfig = RequestConfig.custom()
//读取目标服务器数据超时时间
.setSocketTimeout(10000)
//连接目标服务器超时时间
.setConnectTimeout(10000)
//从连接池获取连接的超时时间
.setConnectionRequestTimeout(10000)
.build();
CloseableHttpClient httpClient = null;
HttpGet request = null;
CloseableHttpResponse response = null;
try {
//设置请求参数
request = new HttpGet(url);
request.setConfig(requestConfig);
//发送请求
httpClient = HttpClients.createDefault();
response = httpClient.execute(request);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_OK) {
HttpEntity entity = response.getEntity();
//输入流
InputStream inputStream = entity.getContent();
//根据ContentType获取文件类型
String fileType = entity.getContentType().getValue();
//得到文件后缀
String suffix = fileType.split("/")[1];
//路径末尾添加'\'
if (!(savePath.endsWith("\\") || savePath.endsWith("/"))) {
savePath += File.separator;
}
//拼接文件保存绝对路径
String filePath = savePath + filename + "." + suffix;
//使用第三方包保存文件
FileUtils.copyToFile(inputStream, new File(filePath));
} else {
throw new HttpResponseException(statusCode, "响应异常");
}
} finally {
if (response != null) {
response.close();
}
if (request != null) {
request.releaseConnection();
}
if (httpClient != null) {
httpClient.close();
}
}
}
- 文件
https://img-home.csdnimg.cn/images/20201124032511.png
- 测试
public static void main(String[] args) {
String url = "https://img-home.csdnimg.cn/images/20201124032511.png";
String savePath = "D:\\";
String filename = "csdn";
try {
downloadFile(url, savePath, filename);
} catch (IOException e) {
e.printStackTrace();
}
}
- 结果
为了方便保存文件,使用了commons-io包中的FileUtils.copyToFile方法,依赖如下:
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
不使用第三方依赖也可自己实现保存文件逻辑,其结果是一样的。
//FileUtils.copyToFile(inputStream, new File(filePath));
BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(filePath));
byte[] buffer = new byte[1024];
int len = 0;
while ((len = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, len);
}
outputStream.close();
inputStream.close();
三、总结
简单介绍了一下HttpClient发送get请求、post请求以及下载文件的使用方法,但HttpClient的使用方法肯定不局限于这几种,还有很多方法这里就不一一列举了,感兴趣的小伙伴可以自己摸索!