大家好,欢迎来到IT知识分享网。
文章目录
刚开始接触对接三方的时候真的一头雾水。不知道从何下手。记录一下。
进入对接群。
1.首先拿到最新三方对接文档。
2.仔细阅读文档,包括发送URL。请求方式POST/GET。需要携带的请求头。请求体。请求头有可能是加密后的密文。具体用什么加密算法,包括校验解密。
3.三方都是需要校验获取token。往往校验这种接口,需要有apiKey,secretKey。找到三方对接人申请这些资料。
4.拿到申请的资料之后,先在postman跑一下,拿到token令牌。
5.postman跑通之后。接下来就需要用Java代码模拟用postman发送请求。
我这里用的是httpclient。
<dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.13</version> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpmime</artifactId> <version>4.5.13</version> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.11.0</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.83</version> </dependency>
package com.xxx.utils; import org.apache.commons.io.IOUtils; import org.apache.http.*; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.config.RequestConfig.Builder; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.utils.HttpClientUtils; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; import org.apache.http.entity.mime.HttpMultipartMode; import org.apache.http.entity.mime.MultipartEntityBuilder; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.apache.http.message.BasicNameValuePair; import org.apache.http.protocol.HTTP; import org.apache.http.util.EntityUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.multipart.MultipartFile; import java.io.*; import java.nio.charset.Charset; import java.util.*; import java.util.Map.Entry; / * @author zyx * @date 2023/3/3 14:23 */ public class HttpUtil {
private static final Logger logger = LoggerFactory.getLogger(HttpUtil.class); private static PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager(); private static RequestConfig requestConfig; public HttpUtil() {
} / * 情况方法直接放这里就行 */ static {
connMgr.setMaxTotal(100); connMgr.setDefaultMaxPerRoute(connMgr.getMaxTotal()); Builder configBuilder = RequestConfig.custom(); configBuilder.setConnectTimeout(60000); configBuilder.setSocketTimeout(70000); configBuilder.setConnectionRequestTimeout(30000); requestConfig = configBuilder.build(); } }
POST请求
POST请求,请求体JSON
/ * post,以 application/json 形式 * @param apiUrl * @param json * @return */ public static String doPost(String apiUrl, String json) {
long start = System.currentTimeMillis(); CloseableHttpClient httpClient = HttpClients.createDefault(); String httpStr = null; HttpPost httpPost = new HttpPost(apiUrl); CloseableHttpResponse response = null; int statusCode = -999; try {
httpPost.setConfig(requestConfig); StringEntity stringEntity = new StringEntity(json.toString(), "UTF-8"); stringEntity.setContentEncoding("UTF-8"); stringEntity.setContentType("application/json"); httpPost.setEntity(stringEntity); response = httpClient.execute(httpPost); HttpEntity entity = response.getEntity(); statusCode = response.getStatusLine().getStatusCode(); httpStr = EntityUtils.toString(entity, "UTF-8"); } catch (Exception var20) {
logger.info("HttpUtil post error:" + var20.getMessage()); var20.printStackTrace(); } finally {
if (response != null) {
try {
EntityUtils.consume(response.getEntity()); } catch (IOException var19) {
var19.printStackTrace(); } } logger.info("request to:{},param:{},response code:{},result:{},cost {} ms", new Object[]{
apiUrl, json, statusCode, httpStr, System.currentTimeMillis() - start}); } return httpStr; }
POST请求,请求体JSON,携带请求头
/ * Post方式 * @param apiUrl * @param json json数据 * @param headerMap 请求头 * @return */ public static String doPost(String apiUrl, String json, Map<String,String> headerMap) {
long start = System.currentTimeMillis(); CloseableHttpClient httpClient = HttpClients.createDefault(); String httpStr = null; HttpPost httpPost = new HttpPost(apiUrl); CloseableHttpResponse response = null; int statusCode = -999; try {
httpPost.setConfig(requestConfig); StringEntity stringEntity = new StringEntity(json.toString(), "UTF-8"); stringEntity.setContentEncoding("UTF-8"); //循环增加header if (headerMap != null) {
Iterator headerIterator = headerMap.entrySet().iterator(); while(headerIterator.hasNext()){
Entry<String,String> elem = (Entry<String, String>) headerIterator.next(); httpPost.addHeader(elem.getKey(),elem.getValue()); } } stringEntity.setContentType("application/json"); httpPost.setEntity(stringEntity); response = httpClient.execute(httpPost); HttpEntity entity = response.getEntity(); statusCode = response.getStatusLine().getStatusCode(); httpStr = EntityUtils.toString(entity, "UTF-8"); } catch (Exception var20) {
logger.info("HttpUtil post error:" + var20.getMessage()); var20.printStackTrace(); } finally {
if (response != null) {
try {
EntityUtils.consume(response.getEntity()); } catch (IOException var19) {
var19.printStackTrace(); } } logger.info("request to:{},param:{},response code:{},result:{},cost {} ms", new Object[]{
apiUrl, json, statusCode, httpStr, System.currentTimeMillis() - start}); } return httpStr; }
POST请求,表单请求体
/ * Post请求 * @param apiUrl 请求链接 * @param params 请求类型:x-www-form-urlencoded * @return */ public static String doPost(String apiUrl, Map<String, Object> params) {
long start = System.currentTimeMillis(); CloseableHttpResponse response = null; String httpStr = null; int statusCode = -999; //创建http实例 CloseableHttpClient httpClient = HttpClients.createDefault(); //创建httpPost实例 HttpPost httpPost = new HttpPost(apiUrl); try {
httpPost.setConfig(requestConfig); List<NameValuePair> pairList = new ArrayList(); Iterator i$ = params.entrySet().iterator(); while(i$.hasNext()) {
Entry<String, Object> entry = (Entry)i$.next(); NameValuePair pair = new BasicNameValuePair((String)entry.getKey(), entry.getValue().toString()); pairList.add(pair); } httpPost.setEntity(new UrlEncodedFormEntity(pairList, Charset.forName("UTF-8"))); response = httpClient.execute(httpPost); statusCode = response.getStatusLine().getStatusCode(); HttpEntity entity = response.getEntity(); httpStr = EntityUtils.toString(entity, "UTF-8"); } catch (Exception e) {
logger.info("HttpUtil发生错误:" + e.getMessage()); e.printStackTrace(); } finally {
if (response != null) {
try {
EntityUtils.consume(response.getEntity()); } catch (IOException e) {
e.printStackTrace(); } } logger.info("request path:{}, param:{},response code:{},result:{},cost {} ms", new Object[]{
apiUrl, params.toString(), statusCode, httpStr, System.currentTimeMillis() - start}); } return httpStr; }
POST请求,表单请求体+文件上传+请求头
url转MultipartFile,MultipartFile转File工具类。
package com.vkl.utils; import org.springframework.web.multipart.MultipartFile; import java.io.*; import java.net.URL; import java.net.URLConnection; / * PDF转换MultipartFile * * @author MrLi * @version 2.0 */ public class PdfToMultipartFile implements MultipartFile {
private static final String FILENAME_TEMPLATE = "%s.%s"; private final byte[] imgContent; private final String type; private final String fileName; private PdfToMultipartFile(byte[] imgContent, String fileName) {
this.imgContent = imgContent; this.fileName = String.format(FILENAME_TEMPLATE, fileName + System.currentTimeMillis(), "pdf"); this.type = "image"; } @Override public String getName() {
return fileName; } @Override public String getOriginalFilename() {
return fileName; } @Override public String getContentType() {
return type; } @Override public boolean isEmpty() {
return imgContent == null || imgContent.length == 0; } @Override public long getSize() {
return imgContent.length; } @Override public byte[] getBytes() {
return imgContent; } @Override public InputStream getInputStream() {
return new ByteArrayInputStream(imgContent); } @Override public void transferTo(File dest) throws IOException, IllegalStateException {
FileOutputStream fileOutputStream = null; try {
fileOutputStream = new FileOutputStream(dest); fileOutputStream.write(imgContent); } finally {
if (fileOutputStream != null) {
fileOutputStream.close(); } } } public static File MultipartFileToFile(MultipartFile file){
File toFile = null; if("".equals(file) || file.getSize()<=0){
file = null; }else {
try {
InputStream inputStream = file.getInputStream(); toFile = new File(file.getOriginalFilename()); inputStreamToFile(inputStream,toFile); } catch (IOException e) {
e.printStackTrace(); } } return toFile; } private static void inputStreamToFile(InputStream inputStream, File toFile) {
FileOutputStream os = null; try {
os = new FileOutputStream(toFile); int byteRead = 0; byte[] buf = new byte[1024*10]; while ((byteRead=inputStream.read(buf,0,1024))!=-1){
os.write(buf,0,byteRead); } } catch (Exception e) {
e.printStackTrace(); }finally {
if(os != null){
try {
os.close(); } catch (IOException e) {
e.printStackTrace(); } } if(inputStream != null){
try {
inputStream.close(); } catch (IOException e) {
e.printStackTrace(); } } } } public static MultipartFile imageUrlToMultipartFile(String fileName, String imageUrl) {
InputStream fileIs = null; ByteArrayOutputStream out = null; try {
if (imageUrl.startsWith("http") || imageUrl.startsWith("https")) {
URL urlObj = new URL(imageUrl); URLConnection urlConnection = urlObj.openConnection(); urlConnection.setConnectTimeout(10000); urlConnection.setReadTimeout(10000); urlConnection.setDoInput(true); urlConnection.setUseCaches(false); fileIs = urlConnection.getInputStream(); if (fileIs != null) {
out = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len; while ((len = fileIs.read(buffer)) > -1) {
out.write(buffer, 0, len); } out.flush(); byte[] b = out.toByteArray(); return new PdfToMultipartFile(b, fileName); } } } catch (Exception e) {
e.printStackTrace(); } finally {
if (fileIs != null) {
try {
fileIs.close(); } catch (IOException e) {
e.printStackTrace(); } } if (out != null) {
try {
out.close(); } catch (IOException e) {
e.printStackTrace(); } } } return null; } }
情况4:方法:
/ * @param url url链接 * @param headMaps 请求头参数 * @param params 请求体参数 * @param multipartFile 上传文件,可上传单文件或者多文件 * @return */ public static String sendMultipartFilePost(String url, Map<String,String> headMaps, Map<String, Object> params, Map<String,MultipartFile> multipartFile) {
CloseableHttpClient httpClient = HttpClients.createDefault(); String result = null; try {
HttpPost httpPost = new HttpPost(url); if(headMaps!=null){
//循环增加header Iterator headerIterator = headMaps.entrySet().iterator(); while(headerIterator.hasNext()){
Map.Entry<String,String> elem = (Map.Entry<String, String>) headerIterator.next(); httpPost.addHeader(elem.getKey(),elem.getValue()); } } //文件上传 MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setCharset(Charset.forName("UTF-8")); //浏览器兼容 builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); //解决中文乱码 ContentType contentType = ContentType.create(HTTP.PLAIN_TEXT_TYPE, HTTP.UTF_8); for (Map.Entry<String, Object> entry : params.entrySet()) {
if(entry.getValue() == null) {
continue; } //类似浏览器表单提交 builder.addTextBody(entry.getKey(), entry.getValue().toString(), contentType); } if(multipartFile != null){
for (Map.Entry<String, MultipartFile> entry: multipartFile.entrySet()){
if(entry.getValue() == null) {
continue; } builder.addBinaryBody(entry.getKey(), entry.getValue().getInputStream(), ContentType.MULTIPART_FORM_DATA, entry.getValue().getOriginalFilename()); } } HttpEntity entity = builder.build(); httpPost.setEntity(entity); //执行提交 HttpResponse response = httpClient.execute(httpPost); HttpEntity responseEntity = response.getEntity(); if (responseEntity != null) {
//将响应内容转换为字符串 result = EntityUtils.toString(responseEntity, Charset.forName("UTF-8")); } } catch (Exception e) {
e.printStackTrace(); } finally {
try {
httpClient.close(); } catch (IOException e) {
e.printStackTrace(); } logger.info("request to:{},param:{},file:{}", new Object[]{
url,params.toString()}); } return result; }
GET请求
GET请求+拼接参数
/ * @param url * @param params 带参数 * @return */ public static String doGet(String url, Map<String, Object> params) {
long start = System.currentTimeMillis(); StringBuffer param = new StringBuffer(); int i = 0; for(Iterator i$ = params.keySet().iterator(); i$.hasNext(); ++i) {
String key = (String)i$.next(); if (i == 0) {
param.append("?"); } else {
param.append("&"); } param.append(key).append("=").append(params.get(key)); } String apiUrl = url + param; String result = null; //创建一个httpClient CloseableHttpClient httpClient = HttpClients.createDefault(); int statusCode = -999; try {
HttpGet httpGet = new HttpGet(apiUrl); HttpResponse response = httpClient.execute(httpGet); statusCode = response.getStatusLine().getStatusCode(); HttpEntity entity = response.getEntity(); if (entity != null) {
InputStream instream = entity.getContent(); result = IOUtils.toString(instream, "UTF-8"); } } catch (Exception var18) {
logger.info("httputil get error:" + var18.getMessage()); var18.printStackTrace(); } finally {
if (httpClient != null) {
//关闭流 HttpClientUtils.closeQuietly(httpClient); } logger.info("request to:{},param:{},response code:{},result:{},cost {} ms", new Object[]{
apiUrl, param.toString(), statusCode, result, System.currentTimeMillis() - start}); } return result; }
GET请求+拼接参数+请求头
/ * 请求方式 Get * @param url 请求链接 * @param params 以 x-www-form-urlencoded * @param headerMap 请求头参数 * @return */ public static String doGet(String url, Map<String, Object> params, Map<String,String> headerMap) {
long start = System.currentTimeMillis(); StringBuffer param = new StringBuffer(); int i = 0; for(Iterator i$ = params.keySet().iterator(); i$.hasNext(); ++i) {
String key = (String)i$.next(); if (i == 0) {
param.append("?"); } else {
param.append("&"); } param.append(key).append("=").append(params.get(key)); } String apiUrl = url + param; String result = null; CloseableHttpClient httpClient = HttpClients.createDefault(); int statusCode = -999; try {
HttpGet httpGet = new HttpGet(apiUrl); //循环增加header if (headerMap != null) {
Iterator headerIterator = headerMap.entrySet().iterator(); while(headerIterator.hasNext()){
Entry<String,String> elem = (Entry<String, String>) headerIterator.next(); httpGet.addHeader(elem.getKey(),elem.getValue()); } } HttpResponse response = httpClient.execute(httpGet); statusCode = response.getStatusLine().getStatusCode(); HttpEntity entity = response.getEntity(); if (entity != null) {
InputStream instream = entity.getContent(); result = IOUtils.toString(instream, "UTF-8"); } } catch (Exception e) {
logger.info("HttpUtil发生错误:" + e.getMessage()); e.printStackTrace(); } finally {
if (httpClient != null) {
HttpClientUtils.closeQuietly(httpClient); } logger.info("request to:{},param:{},response code:{},result:{},cost {} ms", new Object[]{
apiUrl, param.toString(), statusCode, result, System.currentTimeMillis() - start}); } return result; }
觉得对你有帮助,点赞收藏一波
免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://haidsoft.com/111213.html