httpclient访问第三方接口分为访问Post请求和访问Get请求.
话不多说,先放get请求访问方法:
data是接口入参,url是接口路径.
public static JSONArray doGet(JSONObject data, String url) {
CloseableHttpClient client = HttpClients.createDefault();
JSONArray jsonObject = null;
String param = null;
List<NameValuePair> list = new ArrayList<>(); //该list为传递给httpClient的参数
//这里加了一个判断,支持字符串拼接的路径
if (url.endsWith("}")) {
Map<String,Object> map = data.toJavaObject(Map.class);
Set set = map.keySet();
int i = 0;
Object[] array = new Object[set.size()];
for (Object key : set) {
array[i++] = map.get(key);
}
param = Arrays.stream(array).map(n -> String.valueOf(n)).collect(Collectors.joining("/"));
//路径非拼接时
}else {
Map map = data.toJavaObject(Map.class);
map.forEach((key,value) -> {
if (value != null){
//键值对类型
BasicNameValuePair basicNameValuePair = new BasicNameValuePair(key.toString(),value.toString());
list.add(basicNameValuePair);
}
});
}
try {
//防止字符乱码
UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(list,"UTF-8");
String params = EntityUtils.toString(urlEncodedFormEntity);
// 要调用的接口方法
HttpGet get = null;
//判断url是拼接
if (url.endsWith("}")) {
get = new HttpGet(url.substring(0,url.indexOf("{"))+"/"+param);
}else {//不是拼接
get = new HttpGet(url+"?"+params);
}
//设置请求头
get.addHeader("content-type", "application/json");
//token
// get.addHeader("Authorization","");
HttpResponse res = client.execute(get);
String response = EntityUtils.toString(res.getEntity());
System.out.println(response);
System.out.println(res.getStatusLine().getStatusCode());
if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
//这里是JSONObject还是JSONArray根据返回结果定
jsonObject = JSONObject.parseArray(response);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
return jsonObject;
}
post请求:
public static JSONObject doPost(JSONObject data, String url) {
CloseableHttpClient client = HttpClients.createDefault();
JSONObject jsonObject = null;
//这里加了一个判断,支持字符串拼接的路径
String param = null;
if (url.endsWith("}")) {
Map<String,Object> map = data.toJavaObject(Map.class);
Set set = map.keySet();
int i = 0;
Object[] array = new Object[set.size()];
for (Object key : set) {
array[i++] = map.get(key);
}
param = Arrays.stream(array).map(n -> String.valueOf(n)).collect(Collectors.joining("/"));
//路径非拼接时
}
try {
// 要调用的接口方法
HttpPost post;
//判断url是拼接
if (url.endsWith("}")) {
post = new HttpPost(url.substring(0,url.indexOf("{"))+"/"+param);
}else {//不是拼接
post = new HttpPost(url);
post.setEntity(new StringEntity(data.toString(),"UTF-8"));
}
post.addHeader("content-type", "application/json");
//post.addHeader("Authorization","Bearer "+ token);
HttpResponse res = client.execute(post);
String response = EntityUtils.toString(res.getEntity());
System.out.println(response);
System.out.println(res.getStatusLine().getStatusCode());
if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
jsonObject = JSONObject.parseObject(response);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
return jsonObject;
}