Posted in Java/Android onAugust 14, 2022
本文实例为大家分享了httpclient调用远程接口的具体代码,供大家参考,具体内容如下
依赖jar包 httpclient:4.5.6.jar httpcore:4.4.3
封装HttpClient接口
package com.example.HttpClient;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
//需要引入的jar包
//compile('org.apache.httpcomponents:httpclient:4.5.6')
//compile('org.apache.httpcomponents:httpcore:4.4.3')
/**
* @program: webservice_demo
* @description: HttpClient工具类
* @author: miaoqixin
* @create: 2018-11-28 16:39
**/
public class HttpClientUtil {
private CloseableHttpClient httpClient;
public HttpClientUtil() {
// 1 创建HttpClinet,相当于打开浏览器
httpClient = HttpClients.createDefault();
}
/* *
* get请求
* @author miaoqixin
* @date 2018/11/28 16:51
* @param [url, map]
* @return HttpResult
*/
public HttpResult doGet(String url, Map<String, Object> map) throws Exception {
// 声明URIBuilder
URIBuilder uriBuilder = new URIBuilder(url);
// 判断参数map是否为非空
if (map != null) {
// 遍历参数
for (Map.Entry<String, Object> entry : map.entrySet()) {
// 设置参数
uriBuilder.setParameter(entry.getKey(), entry.getValue().toString());
}
}
// 2 创建httpGet对象,相当于设置url请求地址
HttpGet httpGet = new HttpGet(uriBuilder.build());
// 3 使用HttpClient执行httpGet,相当于按回车,发起请求
CloseableHttpResponse response = null;
try {
response = httpClient.execute(httpGet);
} catch (IOException e) {
HttpResult httpResult = new HttpResult();
httpResult.setCode(404);
httpResult.setBody("请求失败");
return httpResult;
}
// 4 解析结果,封装返回对象httpResult,相当于显示相应的结果
// 状态码
// response.getStatusLine().getStatusCode();
// 响应体,字符串,如果response.getEntity()为空,下面这个代码会报错,所以解析之前要做非空的判断
// EntityUtils.toString(response.getEntity(), "UTF-8");
HttpResult httpResult = new HttpResult();
// 解析数据封装HttpResult
if (response.getEntity() != null) {
//httpResult = new HttpResult(response.getStatusLine().getStatusCode(),EntityUtils.toString(response.getEntity(),"UTF-8"));
httpResult.setCode(response.getStatusLine().getStatusCode());
httpResult.setBody(EntityUtils.toString(response.getEntity(),"UTF-8"));
} else {
//httpResult = new HttpResult(response.getStatusLine().getStatusCode(), "");
httpResult.setCode(response.getStatusLine().getStatusCode());
//httpResult.setBody("");
}
// 返回
return httpResult;
}
/* *
* post请求
* @author miaoqixin
* @date 2018/11/28 18:13
* @param [url, map]
* @return com.example.HttpClient.HttpResult
*/
public HttpResult doPost(String url, Map<String, Object> map) throws Exception {
// 声明httpPost请求
HttpPost httpPost = new HttpPost(url);
// 判断map不为空
if (map != null) {
// 声明存放参数的List集合
List<NameValuePair> params = new ArrayList<NameValuePair>();
// 遍历map,设置参数到list中
for (Map.Entry<String, Object> entry : map.entrySet()) {
params.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
}
// 创建form表单对象
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(params, "UTF-8");
// 把表单对象设置到httpPost中
httpPost.setEntity(formEntity);
}
// 使用HttpClient发起请求,返回response
CloseableHttpResponse response = null;
try {
response = httpClient.execute(httpPost);
} catch (IOException e) {
HttpResult httpResult = new HttpResult();
httpResult.setCode(404);
httpResult.setBody("请求失败");
return httpResult;
}
// 解析response封装返回对象httpResult
HttpResult httpResult = new HttpResult();
// 解析数据封装HttpResult
if (response.getEntity() != null) {
//httpResult = new HttpResult(response.getStatusLine().getStatusCode(),EntityUtils.toString(response.getEntity(),"UTF-8"));
httpResult.setCode(response.getStatusLine().getStatusCode());
httpResult.setBody(EntityUtils.toString(response.getEntity(),"UTF-8"));
} else {
//httpResult = new HttpResult(response.getStatusLine().getStatusCode(), "");
httpResult.setCode(response.getStatusLine().getStatusCode());
//httpResult.setBody("");
}
// 返回结果
return httpResult;
}
/* *
* Put请求
* @author miaoqixin
* @date 2018/11/28 18:14
* @param [url, map]
* @return com.example.HttpClient.HttpResult
*/
public HttpResult doPut(String url, Map<String, Object> map) throws Exception {
// 声明httpPost请求
HttpPut httpPut = new HttpPut(url);
// 判断map不为空
if (map != null) {
// 声明存放参数的List集合
List<NameValuePair> params = new ArrayList<NameValuePair>();
// 遍历map,设置参数到list中
for (Map.Entry<String, Object> entry : map.entrySet()) {
params.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
}
// 创建form表单对象
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(params, "UTF-8");
// 把表单对象设置到httpPost中
httpPut.setEntity(formEntity);
}
// 使用HttpClient发起请求,返回response
CloseableHttpResponse response = null;
try {
response = httpClient.execute(httpPut);
} catch (IOException e) {
HttpResult httpResult = new HttpResult();
httpResult.setCode(404);
httpResult.setBody("请求失败");
return httpResult;
}
// 解析response封装返回对象httpResult
HttpResult httpResult = new HttpResult();
// 解析数据封装HttpResult
if (response.getEntity() != null) {
//httpResult = new HttpResult(response.getStatusLine().getStatusCode(),EntityUtils.toString(response.getEntity(),"UTF-8"));
httpResult.setCode(response.getStatusLine().getStatusCode());
httpResult.setBody(EntityUtils.toString(response.getEntity(),"UTF-8"));
} else {
//httpResult = new HttpResult(response.getStatusLine().getStatusCode(), "");
httpResult.setCode(response.getStatusLine().getStatusCode());
//httpResult.setBody("");
}
// 返回结果
return httpResult;
}
/* *
* Delete请求
* @author miaoqixin
* @date 2018/11/28 18:20
* @param [url, map]
* @return com.example.HttpClient.HttpResult
*/
public HttpResult doDelete(String url, Map<String, Object> map) throws Exception {
// 声明URIBuilder
URIBuilder uriBuilder = new URIBuilder(url);
// 判断参数map是否为非空
if (map != null) {
// 遍历参数
for (Map.Entry<String, Object> entry : map.entrySet()) {
// 设置参数
uriBuilder.setParameter(entry.getKey(), entry.getValue().toString());
}
}
// 2 创建httpGet对象,相当于设置url请求地址
HttpDelete httpDelete = new HttpDelete(uriBuilder.build());
// 3 使用HttpClient执行httpGet,相当于按回车,发起请求
CloseableHttpResponse response = null;
try {
response = httpClient.execute(httpDelete);
} catch (IOException e) {
HttpResult httpResult = new HttpResult();
httpResult.setCode(404);
httpResult.setBody("请求失败");
return httpResult;
}
// 4 解析结果,封装返回对象httpResult,相当于显示相应的结果
// 状态码
// response.getStatusLine().getStatusCode();
// 响应体,字符串,如果response.getEntity()为空,下面这个代码会报错,所以解析之前要做非空的判断
// EntityUtils.toString(response.getEntity(), "UTF-8");
HttpResult httpResult = new HttpResult();
// 解析数据封装HttpResult
if (response.getEntity() != null) {
//httpResult = new HttpResult(response.getStatusLine().getStatusCode(),EntityUtils.toString(response.getEntity(),"UTF-8"));
httpResult.setCode(response.getStatusLine().getStatusCode());
httpResult.setBody(EntityUtils.toString(response.getEntity(),"UTF-8"));
} else {
//httpResult = new HttpResult(response.getStatusLine().getStatusCode(), "");
httpResult.setCode(response.getStatusLine().getStatusCode());
//httpResult.setBody("");
}
// 返回
return httpResult;
}
}
创建HttpClient调用接口的返回实体
package com.example.HttpClient;
import lombok.Data;
import java.io.Serializable;
/**
* @program: webservice_demo
* @description: HttpClient返回对象
* @author: miaoqixin
* @create: 2018-11-28 16:54
**/
@Data
public class HttpResult implements Serializable {
// 响应的状态码
private int code;
// 响应的响应体
private String body;
}
然后用我们通过junit来测试一下接口
package com.example.HttpClient;
import org.junit.Before;
import org.junit.Test;
import java.util.HashMap;
import java.util.Map;
/**
* @program: webservice_demo
* @description: 调用测试
* @author: miaoqixin
* @create: 2018-11-28 17:21
**/
public class APIServiceTest {
private HttpClientUtil apiService;
@Before
public void init() {
this.apiService = new HttpClientUtil();
}
// 查询
@Test
public void testQueryItemById() throws Exception {
// http://manager.aaaaaa.com/rest/item/interface/{id}
String url = "https://www.apiopen.top/weatherApi";
Map<String, Object> map = new HashMap<>();
//map.put("id",22222);
//map.put("name",33333);
HttpResult httpResult = apiService.doGet(url,map);
System.out.println(httpResult.getCode());
System.out.println(httpResult.getBody());
}
// 新增
@Test
public void testSaveItem() throws Exception {
// http://manager.aaaaaa.com/rest/item/interface/{id}
String url = "https://www.i12368.com/preservation/auth/checkUsera";
Map<String, Object> map = new HashMap<String, Object>();
// title=测试RESTful风格的接口&price=1000&num=1&cid=888&status=1
map.put("userId", 12343474);
HttpResult httpResult = apiService.doPost(url, map);
System.out.println(httpResult.getCode());
System.out.println(httpResult.getBody());
}
// 修改
@Test
public void testUpdateItem() throws Exception {
// http://manager.aaaaaa.com/rest/item/interface/{id}
String url = "http://manager.aaaaaa.com/rest/item/interface";
Map<String, Object> map = new HashMap<String, Object>();
// title=测试RESTful风格的接口&price=1000&num=1&cid=888&status=1
map.put("title", "测试APIService调用修改接口");
map.put("id", "44");
HttpResult httpResult = apiService.doPut(url, map);
System.out.println(httpResult.getCode());
System.out.println(httpResult.getBody());
}
// 删除
@Test
public void testDeleteItemById() throws Exception {
// http://manager.aaaaaa.com/rest/item/interface/{id}
String url = "http://manager.aaaaaa.com/rest/item/interface/44";
Map<String, Object> map = new HashMap<String, Object>();
map.put("id", "44");
HttpResult httpResult = apiService.doDelete(url, map);
System.out.println(httpResult.getCode());
System.out.println(httpResult.getBody());
}
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。
httpclient调用远程接口的方法
- Author -
@小花- Original Sources -
声明:登载此文出于传递更多信息之目的,并不意味着赞同其观点或证实其描述。
Reply on: @reply_date@
@reply_contents@