java使用http工具类调用第三方接口
java使用http工具类调用第三方接口
一、所需maven依赖:
<!--json依赖-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.75</version>
<scope>compile</scope>
</dependency>
<!--gson-->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.6</version>
</dependency>
<!--lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.18</version>
</dependency>
二、用到的http工具类:
1.hutool的HttpUtil
所需maven依赖如下:
<!--hutool-->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.1.2</version>
</dependency>
2.HttpClientUtils
代码如下:
package com.pasture.pastureService.common.utils;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
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.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;
/**
* @Classname HttpClientUtils
* @Description http请求工具类
* @Date 2022/3/4 18:08
* @Created by 小郭
*/
@Slf4j
public class HttpClientUtils {
private static RequestConfig requestConfig = null;
static
{
// 设置请求和传输超时时间
requestConfig = RequestConfig.custom().setSocketTimeout(5000).setConnectTimeout(5000).build();
}
/**
* post请求传输json参数
* @param url url地址
* @return
*/
public static JSONObject httpPost2(String url, JSONObject jsonParam)
{
// post请求返回结果
CloseableHttpClient httpClient = HttpClients.createDefault();
JSONObject jsonResult = null;
HttpPost httpPost = new HttpPost(url);
// 设置请求和传输超时时间
httpPost.setConfig(requestConfig);
try
{
if (null != jsonParam)
{
// 解决中文乱码问题
StringEntity entity = new StringEntity(jsonParam.toString(), "utf-8");
entity.setContentEncoding("UTF-8");
entity.setContentType("application/json");
httpPost.setEntity(entity);
}
CloseableHttpResponse result = httpClient.execute(httpPost);
// 请求发送成功,并得到响应
if (result.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
{
String str = "";
try
{
// 读取服务器返回过来的json字符串数据
str = EntityUtils.toString(result.getEntity(), "utf-8");
// 把json字符串转换成json对象
jsonResult = JSONObject.parseObject(str);
}
catch (Exception e)
{
log.error("post请求提交失败:" + url, e);
}
}
}
catch (IOException e)
{
log.error("post请求提交失败:" + url, e);
}
finally
{
httpPost.releaseConnection();
}
return jsonResult;
}
/**
* post请求传输String参数 例如:name=Jack&sex=1&type=2
* Content-type:application/x-www-form-urlencoded
* @param url url地址
* @param strParam 参数
* @return
*/
public static JSONObject httpPost(String url, String strParam)
{
// post请求返回结果
CloseableHttpClient httpClient = HttpClients.createDefault();
JSONObject jsonResult = null;
HttpPost httpPost = new HttpPost(url);
httpPost.setConfig(requestConfig);
try
{
if (null != strParam)
{
// 解决中文乱码问题
StringEntity entity = new StringEntity(strParam, "utf-8");
entity.setContentEncoding("UTF-8");
entity.setContentType("application/x-www-form-urlencoded");
httpPost.setEntity(entity);
}
CloseableHttpResponse result = httpClient.execute(httpPost);
// 请求发送成功,并得到响应
if (result.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
{
String str = "";
try
{
// 读取服务器返回过来的json字符串数据
str = EntityUtils.toString(result.getEntity(), "utf-8");
// 把json字符串转换成json对象
jsonResult = JSONObject.parseObject(str);
}
catch (Exception e)
{
log.error("post请求提交失败:" + url, e);
}
}
}
catch (IOException e)
{
log.error("post请求提交失败:" + url, e);
}
finally
{
httpPost.releaseConnection();
}
return jsonResult;
}
/**
* 发送get请求
* @param url 路径
* @return
*/
public static JSONObject httpGet(String url)
{
// get请求返回结果
JSONObject jsonResult = null;
CloseableHttpClient client = HttpClients.createDefault();
// 发送get请求
HttpGet request = new HttpGet(url);
request.setConfig(requestConfig);
try
{
CloseableHttpResponse response = client.execute(request);
// 请求发送成功,并得到响应
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
{
// 读取服务器返回过来的json字符串数据
HttpEntity entity = response.getEntity();
String strResult = EntityUtils.toString(entity, "utf-8");
// 把json字符串转换成json对象
jsonResult = JSONObject.parseObject(strResult);
}
else
{
log.error("get请求提交失败:" + url);
}
}
catch (IOException e)
{
log.error("get请求提交失败:" + url, e);
}
finally
{
request.releaseConnection();
}
return jsonResult;
}
}
三、代码示例如下:
package com.pasture.pastureService.modules.third;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.pasture.pastureService.common.utils.HttpClientUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.Map;
/**
* @Classname AmapSDK
* @Description:高德地图相关接口对接
* https://lbs.amap.com/api/track/lieying-kaifa/api/grasproad
* 创建服务
* 创建终端
* 轨迹上传
* 轨迹查询
* @Date: 2023-11-09 14:25
* @AUTHOR: 无泪之城
* @Version 1.0
*/
@Slf4j
@Component
public class GdMapSDK {
@Value("${gdMap.key}")
private String key;//高德地图key
@Value("${gdMap.sid}")
private String sid;//高德猎鹰轨迹服务-服务id
/**
* 创建服务
* 创建服务(sid):一个key最多能创建15个服务,创建一个就够了-【可以通过此请求,在对应的 Key 下增加 1 个 Service,Service 增加成功后会返回 Service 的 id。每个 Key 下最多注册15个 Service】
* @return
*/
public Map<String,Object> createService(){
String baseUrl = "https://tsapi.amap.com/v1/track/service/add";
Map<String,Object> params=new HashMap<>();
params.put("key", key);
params.put("name", "muCaoService");
String s = HttpUtil.post(baseUrl, params);
Map<String, Object> resultMap=new HashMap<>();
resultMap.put("result",s);
return resultMap;
}
/**
* 查询服务
* @return
*/
public Map<String,Object> getService(){
String baseUrl = "https://tsapi.amap.com/v1/track/service/list?key=b2944557ea0ce4b4acd6280ccd03df2c";
JSONObject jsonObject = HttpClientUtils.httpGet(baseUrl);
//3.对微信返回的数据进行转换
Gson gson = new Gson();
Map<String, Object> resultMap = gson.fromJson(String.valueOf(jsonObject), HashMap.class);
log.info("返回用户数据:{}",resultMap);
return resultMap;
}
/**
* 创建终端(tid)
* 创建终端(tid):一个服务下可以创建100000个终端-【 每次调用此接口,可以在指定 Service 下创建1个终端,默认最大支持创建100000个】
* @param weChatUserId
* @return
*/
public String createTerminal(String weChatUserId){
String baseUrl = "https://tsapi.amap.com/v1/track/terminal/add";
Map<String,Object> params=new HashMap<>();
params.put("key", key);
params.put("sid", sid);
params.put("name", "terminal_"+weChatUserId);
String result = HttpUtil.post(baseUrl, params);
JSONObject json= JSON.parseObject(result);
String data = json.getString("data");
JSONObject jasonData = JSON.parseObject(data);
String tid=jasonData.getString("tid");
return tid;
}
/**
* 查询终端(tid)
* @return
*/
public static Map<String,Object> getTerminal(){
String baseUrl = "https://tsapi.amap.com/v1/track/terminal/list?key=b2944557ea0ce4b4acd6280ccd03df2c&sid=1009253";
JSONObject jsonObject = HttpClientUtils.httpGet(baseUrl);
//3.对微信返回的数据进行转换
Gson gson = new Gson();
Map<String, Object> resultMap = gson.fromJson(String.valueOf(jsonObject), HashMap.class);
log.info("返回用户数据:{}",resultMap);
return resultMap;
}
//创建轨迹(trid):【创建一条轨迹,一个终端下最多可创建500000条轨迹。】
//轨迹点上传:在上传经纬度之前需要先通过创建轨迹接口创建一条轨迹,拿到trid,根据trid上传经纬度点;
//轨迹查询:查询某条指定轨迹:指定服务id、终端id、轨迹id,查询指定的轨迹信息,单次最多查询一条轨迹;
// public static void main(String[] args) {
//// Map map = GdMapSDK.createService();
//// String s = GdMapSDK.createTerminal("8888");
//// Map map = GdMapSDK.getTerminal();
//// System.out.println(s);
// }
}
本文来自博客园,作者:青喺半掩眉砂,转载请注明原文链接:https://www.cnblogs.com/xiaoguo-java/p/17869718.html