RestTemplate
配置
这是SpringBoot 的基础框架,只要使用SpringBoot,就不需要再单独引用,这里只是简单记录下
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
初始化配置
有两种配置方式:
一:初始化到Bean容器里
package com.mt.visitor.service.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
@Configuration
//@LoadBalanced 此注解用于在RestTemplate上启用客户端负载均衡,根据实际情况看是否添加
public class AfterInitConfig implements ApplicationRunner {
@Bean //@Bean注解通常与 @Configuration注解 一起使用
public RestTemplate restTemplate(){
return new RestTemplate();//第一种简单设置即可方式
/**
* 第二种方式,配置上连接超时时间
* SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
* requestFactory.setConnectTimeout(1000 * 60 * 60 * 10);//连接超时时间
* requestFactory.setReadTimeout(1000 * 60 * 60 * 10);//读取超时时间
* return new RestTemplate(requestFactory);
*/
}
}
二:直接 New 出来使用
package com.mt.visitor.service.service.impl;
import com.alibaba.fastjson.JSONObject;
import com.mt.visitor.service.entity.PositionRegister;
import com.mt.visitor.service.mapper.PositionRegisterMapper;
import com.mt.visitor.service.service.IPositionRegisterService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
/**
* <p>
* 扫码登记用位置表 服务实现类
* </p>
*
* @author ${author}
* @since 2022-08-26
*/
@Service
public class PositionRegisterServiceImpl extends ServiceImpl<PositionRegisterMapper, PositionRegister> implements IPositionRegisterService {
private RestTemplate restTemplate = new RestTemplate(); //第二种初始化方式
@Value("${properties.createQrCodeUrl}")
private String createQrCodeUrl;
/**
* @Autowired
* RestTemplate restTemplate; // 第一种初始化方式通过 @Autowired 从Bean中取出使用
*/
@Override
public String createQrCode(String adc, String type, String lineColor) {
String qrCode = null;
try{
// String url = "https://dahuang.nicaicai.com/haha/nishishei/buzhidao";
String url = createQrCodeUrl;
JSONObject jsonObject = new JSONObject();
jsonObject.put("adc",adc);
jsonObject.put("type",type);
jsonObject.put("lineColor",lineColor);
ResponseEntity<JSONObject> responseEntity = restTemplate.postForEntity(url, jsonObject, JSONObject.class);
//响应体
JSONObject body = responseEntity.getBody();
JSONObject resData = body.getJSONObject("resData");
qrCode = resData.getString("qrCode");
}catch (Exception e){
e.printStackTrace();
}
return qrCode;
}
}
Get请求
@Autowired
private RestTemplate restTemplate;
/**
* 带参的get请求
*/
@Test
public void getByParam(){
/**
* 如果有请求头,可以封装请求头
* HttpHeaders headers = new HttpHeaders();
* headers.add("token", "888888");
* HttpEntity<MultiValueMap<String, Object>> formEntity = new HttpEntity<>(headers);
*/
//请求地址
String url = "http://dahuang.yujizi.com/taigu?userName={userName}&userPwd={userPwd}";
//String url2 = "http://dahuang.yujizi.com/taigu/{1}/{2}"
//String url3 = UriComponentsBuilder.fromHttpUrl("http://dahuang.yujizi.com/taigu")
// .queryParam("param1", j)
// .queryParam("param2", "value2")
// .toUriString();
//请求参数
Map<String, String> uriVariables = new HashMap<>();
uriVariables.put("userName", "李子柒");
uriVariables.put("userPwd", "666666");
//发起请求,直接返回对象(带参数请求)
ResponseBean responseBean = restTemplate.getForObject(url, ResponseBean.class, uriVariables);
//ResponseBean responseBean = restTemplate.getForObject(url2 , ResponseBean.class, "李子柒", "666666");
//ResponseEntity<Map> exchange = restTemplate.exchange(url3, HttpMethod.GET, formEntity, Map.class);
System.out.println(responseBean.toString());
}
/**
* 不带参的get请求
* getForEntity 的用法和 getForObject 一样,只是多出来点东西
*/
@Test
public void getBy(){
//请求地址
String url = "http://dahuang.yujizi.com/taigu";
//发起请求,直接返回对象
ResponseBean responseBean = restTemplate.getForObject(url, ResponseBean.class, uriVariables);
System.out.println(responseBean.toString());
//发起请求,返回全部信息
ResponseEntity<ResponseBean> response = restTemplate.getForEntity(url, ResponseBean.class);
// 打印获取响应体
System.out.println("响应体:" + response.getBody().toString());
// getForEntity会比getForObject多出来以下内容
HttpStatus statusCode = response.getStatusCode();//响应状态
int statusCodeValue = response.getStatusCodeValue();//响应状态码
HttpHeaders headers = response.getHeaders();//Headers信息
}
Post 请求
@Autowired
RestTemplate restTemplate; // 第一种初始化方式通过 @Autowired 从Bean中取出使用
@Override
public String createQrCode(String adc, String type, String lineColor) {
String qrCode = null;
try{
String url = "http://dahuang.yujizi.com/taigu";
JSONObject jsonObject = new JSONObject();
jsonObject.put("adc",adc);
jsonObject.put("type",type);
jsonObject.put("lineColor",lineColor);
ResponseEntity<JSONObject> responseEntity = restTemplate.postForEntity(url, jsonObject, JSONObject.class);
//响应体
JSONObject body = responseEntity.getBody();
JSONObject resData = body.getJSONObject("resData");
qrCode = resData.getString("qrCode");
}catch (Exception e){
e.printStackTrace();
}
return qrCode;
}
Hutool
配置
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.8.18</version>
</dependency>
Post 请求
package com.mt.hengheng.nicai.service;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
@Component
@Slf4j
public class Liziqian {
@Value("${heihei.apiServer}")
private String nicaiApiServer;
private String getToken() {
String url = heiheiApiServer + "/nicaicai/token?grant_type=client_credentials";
HttpResponse response = HttpRequest.post(url).header("Authorization", authHeadValue)
.timeout(30000).setConnectionTimeout(30000)
.execute();
HashMap<String,Object> reqData = new HashMap<>();
reqData.put("authString",authString);
reqData.put("authHeadValue",authHeadValue);
if (response.isOk()) {
String result = response.body();
apiLogService.addApiLog("获取token",url,new JSONObject(reqData).toString(),result);
JSONObject jsonObject = JSONUtil.parseObj(result);
return jsonObject.getStr("access_token");
} else {
apiLogService.addApiLog("获取token",url,new JSONObject(reqData).toString(),"调用失败:"+response.getStatus());
return "";
}
}
public String bujiaoche(String idCard, int personType, String personName, LocalDateTime time,
String stationId, String stationName){
String url = nicaiApiServer+ "/nicaicai/record/fix";
String token = getToken();
if (token == null) {
return null;
}
/*
{
"idCard": "string",
"personType": 1,
"personName": "string",
"datetime": "string",
"recordType": 3,
"operator": "string",
"reason": "string",
"stationId": "string",
"stationName": "string"
}
*/
JSONObject json = new JSONObject();
json.putIfAbsent("idCard", encryptIdCard(idCard));
json.putIfAbsent("personType", personType);
json.putIfAbsent("personName", personName);
json.putIfAbsent("datetime", formatTime(time));
json.putIfAbsent("recordType", 5);
json.putIfAbsent("operator", "系统");
json.putIfAbsent("reason", "系统吵吵");
json.putIfAbsent("stationId", stationId);
json.putIfAbsent("stationName", stationName);
HttpResponse response = HttpRequest.post(url).body(json.toStringPretty())
.header("Content-Type", "application/json")
.header("Authorization", "Bearer " + token)
.timeout(30000).setConnectionTimeout(30000)
.execute();
HashMap<String,Object> reqData = new HashMap<>();
reqData.put("reqData",json);
if (response.isOk()) {
String result = response.body();
apiLogService.addApiLog("强制",url,new JSONObject(reqData).toString(),result);
json = JSONUtil.parseObj(result);
return json.getStr("data");
}
apiLogService.addApiLog("吵吵",url,new JSONObject(reqData).toString(),"调用失败:"+response.getStatus());
return null;
}
}
Get 请求
@ActiveProfiles("test")
@SpringBootTest
public class FindRecord {
@Test
public void testHttpGet(){
// 1. 指定 url 地址
HttpRequest httpRequest = new HttpRequest("http://127.0.0.1:8000/test");
//设置请求方式
httpRequest.setMethod(Method.GET);
// 2、配置请求头和连接超时时间等
String testHeadValue = "Basic " + Base64Encoder.encode("Token");
httpRequest.header("Authorization", testHeadValue).timeout(30000)
.setConnectionTimeout(30000);
// 3. 配置请求参数
Map<String, Object> params = new HashMap<>();
params.put("name", "一人之下");
params.put("id", "柒");
httpRequest.form(params);
// 4. 发起请求,得到http响应体
HttpResponse res = httpRequest.execute();
// 5. 根据实际业务处理响应体
System.out.println(res.body());
}
}