java使用httpclient调用其他http接口
本文经测试可用,直接创建工具类进行调用即可。
工具类代码如下:
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
public class HttpCallOtherInterfaceUtils {
//post请求
public static String callOtherInterface(JSONObject jsonParam,String httpUrl, String postUrl) {
//第一步 创建httpClient对象
HttpClient client = HttpClients.createDefault();
// 要调用的接口方法
String url = httpUrl + postUrl;
//第二步 创建httpPost对象
HttpPost post = new HttpPost(url);
JSONObject jsonObject = null;
try {
//第三步 给getPost设置JSON格式的参数
StringEntity entity = new StringEntity(jsonParam.toJSONString(), "UTF-8");
// entity.setContentEncoding("UTF-8");
// entity.setContentType(ContentType.APPLICATION_JSON.toString());
post.setEntity(entity);
post.setHeader("content-type", "application/json;charset=UTF-8");
//第四步 发送HttpPost请求 获取返回值
HttpResponse res = client.execute(post);
if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
// 返回json格式:
jsonObject = JSONObject.parseObject(EntityUtils.toString(res.getEntity()));
}
} catch (Exception e) {
System.out.println("服务间接口调用出错!");
e.printStackTrace();
//throw new RuntimeException(e);
}finally {
try {
((CloseableHttpClient) client).close();
} catch (IOException e) {
e.printStackTrace();
}
}
return jsonObject.toString();
}
//get请求
public static String doGet(String url) {
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
String result = "";
try {
// 通过址默认配置创建一个httpClient实例
httpClient = HttpClients.createDefault();
// 创建httpGet远程连接实例
HttpGet httpGet = new HttpGet(url);
//模拟浏览器请求访问线上接口
httpGet.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:50.0) Gecko/20100101 Firefox/50.0");
// 设置请求头信息,鉴权
// httpGet.setHeader("Authorization","Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0");
// 设置配置请求参数
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000)// 连接主机服务超时时间
.setConnectionRequestTimeout(35000)// 请求超时时间
.setSocketTimeout(60000)// 数据读取超时时间
.build();
// 为httpGet实例设置配置
httpGet.setConfig(requestConfig);
// 执行get请求得到返回对象
response = httpClient.execute(httpGet);
// 通过返回对象获取返回数据
HttpEntity entity = response.getEntity();
// 通过EntityUtils中的toString方法将结果转换为字符串
result = EntityUtils.toString(entity);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 关闭资源
if (null != response) {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != httpClient) {
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return result;
}
}
注:本文代码测试没问题,我在post请求调用接口时遇到一个问题,发现接口请求收到了但是无论如何也传递不过去参数,经过排查是接收端的问题,我调用的接口是使用jfinal框架写的,所以需要接收端使用HttpKit.readData(getRequest())来接收参数。
如下:
public void studentInfo(String studentId) {
String data = HttpKit.readData(getRequest());
JSONObject jsonObject = JSONObject.parseObject(data);
renderJSON(SystemCode.SYSTEM_OK,StudentService.DAO.findById((String) jsonObject.get("studentId")));
}
通过这样收参就可以接到参数了,所以遇到参数传不过去的问题时,需要排查是不是接收端的问题。