本文主要为了让大家直接复制代码直接用,下述代码是jdk11可直接运行的,但有时jdk8会报错,索性在文章末尾加了段jdk8原始调用第三方接口的代码
Maven依赖
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpmime -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.3.6</version>
</dependency>
import内容:
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.List;
import java.util.Map;
Post接口请求第三方接口
PostMethod postMethod = new PostMethod("你的uri");
//添加请求头数据(一下二选一)
postMethod.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
// postMethod.setRequestHeader("Content-Type", "application/json");
//添加token(非必填!)
// postMethod.setRequestHeader("token", "你的token");
//如果是requestBody请求,就用下面的代码
//参数设置,需要注意的就是里边不能传NULL,要传空字符串
NameValuePair[] data = {
//有几个请求参数就加几个
new NameValuePair("参数1", "参数1的值"),
new NameValuePair("参数2","参数2的值"),
new NameValuePair("参数3","参数3的值")
};
postMethod.setRequestBody(data);
//上面的代码也可以换成这个(某些api可能会有多个相同的key对应多个不同的值)
//postMethod.addParameter(new NameValuePair("参数1", "参数1的值") );
//postMethod.addParameter(new NameValuePair("参数1", "参数1的另一个值") );
//postMethod.addParameter(new NameValuePair("参数2", "参数2的值") );
//postMethod.addParameter(new NameValuePair("参数3", "参数3的值") );
//如果是拼接url后的参数,就用下面的代码
// HttpMethodParams params = new HttpMethodParams();
// //有几个请求参数就加几个
// params.setParameter("参数1", "参数1的值"));
// params.setParameter("参数2", "参数2的值");
// postMethod.setParams(params);
//如果是传实体类,则用下面代码
//RequestEntity entity = new StringRequestEntity(JSONUtil.toJsonStr(你的实体类), "application/json", "UTF-8");
//postMethod.setRequestEntity(entity);
//使用HttpClient执行请求
org.apache.commons.httpclient.HttpClient httpClient = new org.apache.commons.httpclient.HttpClient();
// 执行POST方法
int response = httpClient.executeMethod(postMethod);
// 解决返回值中文乱码
postMethod.getParams().setContentCharset("UTF-8");
//执行完毕,根据postMethod获取数据
String result = postMethod.getResponseBodyAsString();
Get接口请求第三方数据
//1.创建 HttpClient
HttpClient client = new HttpClient();
//2.构造GetMethod的实例
//有几个请求参数,url后面就拼接几个
GetMethod getMethod = new GetMethod("你的url?请求参数1="+请求参数1的值+"&请求参数2="+请求参数2的值);
//可以用 getMethod.addRequestHeader设置你的请求头
getMethod.addRequestHeader("Content-Type", "text/html; charset=UTF-8");
//执行getMethod
int i = client.executeMethod(getMethod);
//getMethod.getResponseBodyAsString()获取返回的json
System.out.println(i + "," + getMethod.getResponseBodyAsString());
// 解决返回值中文乱码
getMethod.getParams().setContentCharset("UTF-8");
JSONObject jsonObject = JSONObject.fromObject(getMethod.getResponseBodyAsString());
String data = jsonObject.getString("data");
System.out.println(data);
带文件的请求
/**
* 带文件的请求
*
* @param url
* @param token
* @param map
* @param files
* @return
*/
public static String fileRequest(String url, String token, Map<String, String> map, List<MultipartFile> files) {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost uploadFile = new HttpPost(url);
if(StringUtils.isNotBlank(token)){
uploadFile.setHeader("token",token);
}
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
//builder.setCharset(Charset.forName("uft-8"));//设置请求的编码格式
if(!map.isEmpty()){
for (Map.Entry<String, String> m : map.entrySet()) {
builder.addTextBody(m.getKey(), m.getValue(), ContentType.TEXT_PLAIN);
}
}
// 把文件加到HTTP的post请求中
for (int i = 0; i < files.size(); i++) {
try {
//假设接受文件的字段名为file
builder.addBinaryBody("file", files.get(i).getInputStream(),
ContentType.MULTIPART_FORM_DATA, files.get(i).getName()
);// 文件流
} catch (IOException e) {
e.printStackTrace();
}
}
HttpEntity multipart = builder.build();
uploadFile.setEntity(multipart);
CloseableHttpResponse response = null;
try {
response = httpClient.execute(uploadFile);
} catch (IOException e) {
e.printStackTrace();
}
HttpEntity responseEntity = response.getEntity();
String result = null;
try {
result = EntityUtils.toString(responseEntity, "UTF-8");
} catch (IOException e) {
e.printStackTrace();
}
//打印请求返回的结果
System.out.println("Post 返回结果" + result);
return result;
}
application/json请求
public static String jsonRequest(String url, String token, Map<String, String> map) {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
// 设置请求的header
httpPost.addHeader("Content-Type", "application/json;charset=utf-8");
httpPost.addHeader("token", token);
// 设置请求的参数
JSONObject jsonParam = new JSONObject();
if(!map.isEmpty()){
for (Map.Entry<String, String> m : map.entrySet()) {
jsonParam.put(m.getKey(), m.getValue());
}
}
StringEntity entity = new StringEntity(jsonParam.toString(), "utf-8");
entity.setContentEncoding("UTF-8");
entity.setContentType("application/json");
httpPost.setEntity(entity);
// 执行请求
HttpResponse response = null;
try {
response = httpClient.execute(httpPost);
} catch (IOException e) {
e.printStackTrace();
}
String result = null;
try {
result = EntityUtils.toString(response.getEntity(), "utf-8");
} catch (IOException e) {
e.printStackTrace();
}
JSONObject jsonObject = JSONUtil.parseObj(result);
System.out.println(jsonObject);
return result;
}
JDK8,原生调用第三方代码如下:
pom maven依赖:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.2</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.5</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>4.4</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.5.13</version>
</dependency>
import部分:
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.znld.aspect.Log;
import org.znld.constants.HttpConstant;
import org.znld.jdy.client.FormDataApiClient;
import org.znld.jdy.model.form.FormDataCreateParam;
import org.znld.jdy.model.form.FormDataDeleteParam;
import org.znld.jdy.model.form.FormDataUpdateParam;
import org.znld.server.ProductServer;
import javax.net.ssl.HttpsURLConnection;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.*;
代码部分:
// 创建连接
URL url = new URL("你的url");
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
//拿到token
String token = "your token";
//根据表数据配置接口参数
Map<String, Object> params = new HashMap<>();
params.put("参数1", 参数1);
params.put("参数2",参数2);
// 设置请求方式
connection.setRequestMethod("POST");
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 设置发送数据的格式json
connection.setRequestProperty("Content-Type", "application/json");
// 设置token appkey
connection.setRequestProperty("token", token);
// 设置接收数据的格式json
connection.setRequestProperty("Accept", "application/json");
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setUseCaches(false);
connection.setInstanceFollowRedirects(true);
OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), StandardCharsets.UTF_8);
// 阿里巴巴的fastjson
out.append(JSONUtil.toJsonStr(params));
out.flush();
out.close();
// 请求成功
int responseCode = connection.getResponseCode();
if (responseCode == 200) {
// 读取响应
StringBuffer respResult = new StringBuffer();
BufferedReader reader = new BufferedReader(
new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8));
String line;
while ((line = reader.readLine()) != null) {
respResult.append(line);
}
reader.close();
// log.info("Req Success{}" + respResult.toString());
System.out.println("Req Success{}" + respResult.toString());
}