Httpcline的 get和post请求
参数为json格式
方法里的参数json都是使用JSON.toJSONString(data) 将一个对象转换为json字符串类型
get
//接口推送 get
private boolean KhartoumProductPushGet(String json,String pushUrl) throws UnsupportedEncodingException {
Date sysdate = Calendar.getInstance().getTime();//获取系统当前时间
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss" );
String t= sdf.format(sysdate);
String str = appId + json + t + secret;//第三方接口要求提供的参数
String sign = dockingUtil.getMD5String(str);//进行md5加密
Boolean result=false;
//创建HttpClient对象
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
json = URLEncoder.encode(json, StandardCharsets.UTF_8);//对携带json数据编码
t = URLEncoder.encode(t, StandardCharsets.UTF_8);//对时间编码
String url=pushUrl + "?appid=" + appId + "&data=" + json +"&t=" + t + "&sign="+sign; //aapid t sign 是第三方需要我们提供的必要参数才能进行请求(看自己第三方接口文档来 顺序也是根据第三方文档) data是我们需要传过去的参数
HttpGet get = new HttpGet(url);
try {
get.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36");
HttpResponse response = httpClient.execute(get);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){//HttpStatus.SC_OK 值 为200
//返回json格式
String res = EntityUtils.toString(response.getEntity());
Map maps=(Map)JSON.parse(res);
if(maps!=null && maps.get("retCode").toString().equals("0")){// 自己根据请求返回值进行判断
//推送成功
}else{
//推送失败
}
}
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
post
post 接口推送数据
public void ProductPushApi(String pushUrl,String jsonParam) {
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
URI uri = UriComponentsBuilder.fromUriString(pushUrl).build().encode().toUri();
var request = new HttpPost(uri);
try {
StringEntity stringEntity = new StringEntity(jsonParam, "UTF-8");
stringEntity.setContentEncoding("UTF-8");
request.setEntity(stringEntity);
request.setHeader("Content-Type","application/json");
request.setHeader("charset","utf-8");
try (var response = httpClient.execute(request)) {
var statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
var entity = response.getEntity();
String body = EntityUtils.toString(entity, StandardCharsets.UTF_8);
var maps = (Map) JSON.parse(body);
boolean success = (boolean) maps.get("success");
if(!success) {
}else{
}
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} catch (ParseException e) {
e.printStackTrace();
}
//********************************************************************************************
//数据推送接口
var apiInfo = apiInfo();
//接口请求数据
var m=new LinkedHashMap();
m.put("apiinfo",apiInfo);
m.put(dataName,data);
String jsonData = JSON.toJSONString(m);
try {
HttpClient client = HttpClient.newBuilder().connectTimeout(Duration.ofMinutes(10)).build();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(pushUrl))
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(jsonData))
.build();
var response = client.send(request, HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8));
if (response.statusCode() == 200 && StringUtils.isNotBlank(response.body())) {
Map pushMap = JSON.parseObject(response.body(), Map.class);
if (Integer.parseInt(pushMap.get("code").toString()) != 1) {
baoNuoProductMapper.insertBaoNuoAddUpdateStatusRecords(LocalDateTime.now(), "推送失败", JSON.toJSONString(jsonData), (String) pushMap.get("msg"));
}
}
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
post根据接口 获取数据
//获取对方接口数据接口方法
public List<Map> getApiDataCommon(String url,Map<String,Object> param) {
Map maps = new HashMap();
List<Map> getDatas= new ArrayList<>();
var httpClient = HttpClientBuilder.create().build();
var uri = UriComponentsBuilder.fromUriString(url).build().encode().toUri();
var request = new HttpPost(uri);
var params = new ArrayList<NameValuePair>();
//请求参数
param.keySet().forEach(key->{
params.add(new BasicNameValuePair(key, param.get(key).toString()));
});
try {
request.setEntity(new UrlEncodedFormEntity(params, StandardCharsets.UTF_8));
try (var response = httpClient.execute(request)) {
var statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
var entity = response.getEntity();
var body = EntityUtils.toString(entity, StandardCharsets.UTF_8);
maps = (Map) JSON.parse(body);
if (maps.get("data") !=null){
getDatas = (List<Map>) maps.get("data");
}
}
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
return getDatas;
}
}