springboot项目整合第三方jar包服务

最近在使用springboot开发的时候,需要用到别人提供的一个图片识别的接口,这个接口是通过j打包成jar的方式提供的

一般来说这种jar的提供方式有两种,一种是提供一个公共方法打成的jar,我们在整合到自己项目的时候,需要将它整合我们的项目里面,

然后在自己的方法里面掉改jar包里面提供的方法

具体的实现方式如下:

(一)

(1) 确认已经配置了maven环境变量

(2)在jar包所在目录打开cmd

(3)输入maven命令打包  mvn install:install-file -DgroupId=com.alipay -DartifactId=trade-sdk -Dversion=1.0.0 -Dpackaging=jar -Dfile=alipay-trade-sdk-1.0.0.jar

其中-DgroupId:表示jar对应的groupId      -DartifactId: 表示jar对应的artifactId      -Dversion: 表示jar对应的 version

(4)在pom文件中引用即可

这样我们在整合jar到自己的项目后,我们再打包项目后,我们的jar里面就有所有需要的依赖了

(二)

还有一种提供jar的方式,就是提供一个单独的可运行的jar 我们本地使用 java -jar 就可以运行,然后使用postman,可以访问提供的接口,这种jar我们不可以直接整合成项目依赖

我们需要在服务器运行该jar 然后再在我们的程序里面使用httpclent来访问该jar,使用这种方法时可以先写一个httpUtil工具类,

其中有一点注意的是,如果该jar是需要上传图片的话,我们不应该把文件流作为参数,我们应该把base64码作为参数,并且需要用json的方式传参

因为如果图片太大的话,直接传参会失败. 具体的参数信息可以问jar的提供者,我们也需要跟jar的提供者说明我们需要的参数类型是base64码,和传参类型是json

(三)

如果提供的jar是单独的可运行程序,我们还有一种最简单的方法,直接在服务器上部署该程序,然后在nginx上配置请求转发路径即可,

此方法是最简单的方法

ps:

常用的httputil工具类

package com.asiainfo.acp.modules.weixin.util;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
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.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
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 java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
* @author zhoubin
* @version 1.0
* @date 2020/6/20 9:53
*/
public class HttpUtil {


private static final Logger LOGGER = LoggerFactory.getLogger(HttpUtil.class);
/**
* 返回成功状态码
*/
private static final int SUCCESS_CODE = 200;

/**
* http get请求
*
* @param url
* @param nameValuePairList
* @return
* @throws Exception
*/
public static JSONObject sendHttpGet(String url, List<NameValuePair> nameValuePairList) throws Exception {
return sendGet(false, url, nameValuePairList, null);
}

public static JSONObject sendHttpsGet(String url, List<NameValuePair> nameValuePairList) throws Exception {
return sendGet(true, url, nameValuePairList, null);
}

public static JSONObject sendRpaGet(String url, List<NameValuePair> nameValuePairList) throws Exception {
Map<String, String> header = new HashMap<>();
header.put("appKey", "jieshou");
header.put("secretKey", "c6a74da990ed4a1d968677d95fa11934");
return sendGet(false, url, nameValuePairList, header);
}

/**
* http Post请求
*
* @param url
* @param param
* @return
* @throws Exception
*/
public static JSONObject sendHttpPost(String url, String param, String contentType) throws Exception {
return sendPost(false, url, param, contentType, null);
}

public static JSONObject sendRpaPost(String url, String param) throws Exception {
Map<String, String> hearder = new HashMap<>();
hearder.put("appKey", "jieshou");
hearder.put("secretKey", "c6a74da990ed4a1d968677d95fa11934");
return sendPost(false, url, param, "application/json;charset=utf-8", hearder);
}

public static JSONObject sendRpaPost(String url, String param, String contentType) throws Exception {
Map<String, String> hearder = new HashMap<>();
hearder.put("appKey", "jieshou");
hearder.put("secretKey", "c6a74da990ed4a1d968677d95fa11934");
return sendPost(false, url, param, contentType, hearder);
}

public static JSONObject sendHttpsPost(String url, String param) throws Exception {
return sendPost(true, url, param, null, null);
}

/**
* 发送GET请求
*
* @param url 请求url
* @param nameValuePairList 请求参数
* @return JSON或者字符串
* @throws Exception
*/
public static JSONObject sendGet(boolean isHttps, String url, List<NameValuePair> nameValuePairList, Map<String, String> header) throws Exception {
JSONObject jsonObject = null;
CloseableHttpClient client = null;
CloseableHttpResponse response = null;
try {
/**
* 创建HttpClient对象
*/
if (isHttps) {
client = SSLClientUtil.getSslClient();
} else {
client = HttpClients.createDefault();
}

/**
* 创建URIBuilder
*/
URIBuilder uriBuilder = new URIBuilder(url);
/**
* 设置参数
*/
if (nameValuePairList != null) {
uriBuilder.addParameters(nameValuePairList);
}

/**
* 创建HttpGet
*/
HttpGet httpGet = new HttpGet(uriBuilder.build());
/**
* 设置请求头部编码
*/
if (header != null) {
for (Map.Entry<String, String> entry : header.entrySet()) {
String mapKey = entry.getKey();
String mapValue = entry.getValue();
httpGet.setHeader(new BasicHeader(mapKey, mapValue));
}
}
httpGet.setHeader(new BasicHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8"));
/**
* 设置返回编码
*/
httpGet.setHeader(new BasicHeader("Accept", "*/*"));
/**
* 请求服务
*/
response = client.execute(httpGet);
/**
* 获取响应吗
*/
int statusCode = response.getStatusLine().getStatusCode();

if (SUCCESS_CODE == statusCode) {
/**
* 获取返回对象
*/
HttpEntity entity = response.getEntity();
/**
* 通过EntityUitls获取返回内容
*/
String result = EntityUtils.toString(entity, "UTF-8");
/**
* 转换成json,根据合法性返回json或者字符串
*/
try {
jsonObject = JSONObject.parseObject(result);
return jsonObject;
} catch (Exception e) {
jsonObject = new JSONObject();
jsonObject.put("error", result);
return jsonObject;
}
} else {
LOGGER.error("HttpClientService-line: {}, errorMsg{}", 97, "GET请求失败!");
}
} catch (Exception e) {
LOGGER.error("HttpClientService-line: {}, Exception: {}", 100, e);
} finally {
response.close();
client.close();
}
return null;
}

/**
* 发送POST请求
*
* @param url
* @param param
* @return JSON或者字符串
* @throws Exception
*/
public static JSONObject sendPost(boolean isHttps, String url, String param, String contentType, Map<String, String> header) throws Exception {
JSONObject jsonObject = null;
CloseableHttpClient client = null;
CloseableHttpResponse response = null;
try {
/**
* 创建一个httpclient对象
*/
if (isHttps) {
client = SSLClientUtil.getSslClient();
} else {
client = HttpClients.createDefault();
}
/**
* 创建一个post对象
*/
HttpPost post = new HttpPost(url);

if (param != null) {
post.setEntity(new StringEntity(param, HTTP.UTF_8));
}

/**
* 设置请求的报文头部的编码
*/
post.setHeader(new BasicHeader("Content-Type", contentType == null ? "application/x-www-form-urlencoded" : contentType));
if (header != null) {
for (Map.Entry<String, String> entry : header.entrySet()) {
String mapKey = entry.getKey();
String mapValue = entry.getValue();
post.setHeader(new BasicHeader(mapKey, mapValue));
}
}
/**
* 设置请求的报文头部的编码
*/
post.setHeader(new BasicHeader("Accept", "*/*"));
/**
* 执行post请求
*/
response = client.execute(post);
/**
* 获取响应码
*/
int statusCode = response.getStatusLine().getStatusCode();
if (SUCCESS_CODE == statusCode) {
/**
* 通过EntityUitls获取返回内容
*/
String result = EntityUtils.toString(response.getEntity(), "UTF-8");
/**
* 转换成json,根据合法性返回json或者字符串
*/
try {
jsonObject = JSONObject.parseObject(result);
return jsonObject;
} catch (Exception e) {
jsonObject = new JSONObject();
jsonObject.put("error", result);
return jsonObject;
}
} else {
LOGGER.error("HttpClientService-line: {}, errorMsg:{}", 146, "POST请求失败!");
}
} catch (Exception e) {
LOGGER.error("HttpClientService-line: {}, Exception:{}", 149, e);
} finally {
response.close();
client.close();
}
return null;
}


public static void main(String[] args) throws Exception {
JSONObject object = sendGet(true, "https://api.huobi.pro/market/trade?symbol=btcusdt", null, null);
System.out.println(object.toJSONString());
}

/**
* 组织请求参数{参数名和参数值下标保持一致}
*
* @param params 参数名数组
* @param values 参数值数组
* @return 参数对象
*/
public static List<NameValuePair> getParams(Object[] params, Object[] values) {
/**
* 校验参数合法性
*/
boolean flag = params.length > 0 && values.length > 0 && params.length == values.length;
if (flag) {
List<NameValuePair> nameValuePairList = new ArrayList<>();
for (int i = 0; i < params.length; i++) {
nameValuePairList.add(new BasicNameValuePair(params[i].toString(), values[i].toString()));
}
return nameValuePairList;
} else {
LOGGER.error("HttpClientService-line: {}, errorMsg:{}", 197, "请求参数为空且参数长度不一致");
}
return null;
}
}




posted @ 2021-05-24 10:55  小猫爱哭鬼  阅读(531)  评论(0编辑  收藏  举报