使用Apache提供的HttpClient对象调用HTTP接口(基于POST请求)
程序员文章站
2024-03-19 22:18:58
...
本篇将主要介绍如何使用HttpClient4.5版本调用接口的实例.(实现代码中有大量注释供理解所用)
先准备好一个Springboot项目,方便自己编写接口与后台直接main方法调用.
Springboot工程结构展示:
准备好后,第一步引入Apache提供的HttpClient4.5版本的依赖包.
依赖如下:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.6</version>
</dependency>
引入好依赖包后,第二步我们先简单的在Controller层中编写基于POST方法的接口.
1.POST请求一般用于提交数据,所以先创建一个User实体类用于自动接收参数.(记得重写toString()方法,方便查看属性值)
public class User {
private int id;
private String username;
private String password;
public User(){
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
'}';
}
}
2.在Controller层,编写POST请求的接口
@ResponseBody
@RequestMapping(value = "/user/save",method = {RequestMethod.POST})
public String saveUserMsg(User user){
//因重写了User的toString()方法,会直接输出属性值
System.out.println(user);
return "保存用户已执行...";
}
由于此接口是基于POST方法的,所以无法在浏览器中测试.可以使用SoapUI或Postman等接口测试工具测试.
第三步,编写HttpClientUtil工具类,然后直接main方法调用POST接口即可.
/**
* 使用HttpClient4.5版本对指定接口路径发送POST请求
* @param httpUrl 指定接口路径
* @param params 接口路径需要携带的参数集
* @return 接口返回的消息
*/
public static String doPost(String httpUrl,Map<String,Object> params){
String result = null;
//声明httpClient,httpResponse于try...catch语句外.方便最后关闭资源
CloseableHttpClient httpClient = null;
CloseableHttpResponse httpResponse = null;
try{
httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(httpUrl);
//HttpEntity是一个接口,所有参数均是通过其子类携带
//声明HttpEntity的实现子类UrlEncodedFormEntity用于携带参数
//UrlEncodedFormEntity构造函数只接受BasicNameValuePair对象,符合程序逻辑
UrlEncodedFormEntity formEntity = null;
if(!params.isEmpty()){
//获取Map集合的键集合
Set<String> keySet = params.keySet();
Iterator iterator = keySet.iterator();
List<NameValuePair> list = new ArrayList<>();
while (iterator.hasNext()){
String key = (String)iterator.next();
Object value = params.get(key);
//BasicNameValuePair通常是用来封装post请求中的参数名称和值
BasicNameValuePair basicNameValuePair = new BasicNameValuePair(key,value.toString());
list.add(basicNameValuePair);
}
//构造器方式注入Entity
formEntity = new UrlEncodedFormEntity(list);
}
//将绑定了参数的HttpEntity子类实现类存入HttpPost对象中
httpPost.setEntity(formEntity);
//设置请求头
httpPost.setHeader("Content-type","application/x-www-form-urlencoded");
//向指定接口发送POST请求
httpResponse = httpClient.execute(httpPost);
if(httpResponse.getStatusLine().getStatusCode()==200){
result = EntityUtils.toString(httpResponse.getEntity());
}
} catch(Exception e){
e.printStackTrace();
} finally {
//逐一关闭使用过的资源
try{
if(httpResponse!=null){
httpResponse.close();
}
if(httpClient!=null){
httpClient.close();
}
}catch (Exception e){
e.printStackTrace();
}
}
return result;
}
第四步,便可以在HttpClientUtil工具类main方法中调用doPost方法.访问POST接口.
public static void main(String[] args) {
Map<String,Object> params = new HashMap<>();
params.put("id",1);
params.put("username","shanghai");
params.put("password","000000");
System.out.println(HttpClientUtil.doPost("http://127.0.0.1:8080/user/save",params));
}
调用结果如下图:
main程序输出返回值如下:
Springboot接口输出结果如下:
以上便完成了使用HttpClient对象向接口发送POST请求的任务