目录
一、RestTemplate 不同方法的调用示例 GET方法,POST方法
2.1 RestTemplate GET请求示例代码
2.2 RestTemplate POST请求示例代码
2.3 RestTemplate Post 通过form提交数据,代码实例
二、RestTemplate 请求参数设置的几种方式
1. URL Path 中携带参数
2. ResponseBody中传递参数,JSON对象传递参数
3. FORM 表单提交参数
http 客户端的工具越来越多,每次使用的时候又各有特点,所以在这里总结下各个http 客户端工具的使用,java代码如下。
常见的http客户端工具有这些:httpClient, okHttp, RestTemplate,jesryClient
【Http客户端】Http客户端-RestTemplate的使用实例代码
今天我们说说 RestTemplate工具
1. 构建一个RestTemplate 的单例bean
当然你也可以直接在方法内部每次使用的时候 new 一个RestTemplate对象。
比如 RestTemplate restTemplate = new RestTemplate(); 也是可以的
@Configuration
public class RestTemplateConfig {
@Bean
public RestTemplate restTemplate(ClientHttpRequestFactory simpleClientHttpRequestFactory) {
return new RestTemplate(simpleClientHttpRequestFactory);
}
@Bean
public ClientHttpRequestFactory simpleClientHttpRequestFactory() {
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
factory.setConnectTimeout(3000);
factory.setReadTimeout(30000);
return factory;
}
}
2. 使用RestTemplate
一、RestTemplate 不同方法的调用示例 GET方法,POST方法
2.1 RestTemplate GET请求示例代码
header参数的设置
requestParameter参数的设置
response数据的解析
void testSendGetHttp() {
// http请求模板
RestTemplate restTemplate = new RestTemplate();
// 设置请求头
HttpHeaders headers = new HttpHeaders();
headers.add("clientId", "123123");
headers.add("secret", "321321");
// url
String url = "https://example.com/user";
// get请求构造url
UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(url)
.queryParam("username", "张三")
.queryParam("email", "");
String path = builder.build().toUri().toString();
log.info("path: {}", path); // 输出https://example.com/user?username=张三&email=
// 封装http实体
HttpEntity<String> entity = new HttpEntity<>(headers);
// 发送请求
ResponseEntity<String> response = restTemplate.exchange(path, HttpMethod.GET, entity, String.class);
log.info("response body: {}", response.getBody());
}
// response 返回值这里用了泛型
private void getDemo(){
// 设置请求头
HttpHeaders headers = new HttpHeaders();
headers.add("Authorization", "bearer " + accessToken);
// get请求构造url
UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(AccountConstants.URL_ACCOUNT_GET_USERINFO_BY_TOKEN);
builder.build("gg");
builder.queryParam("a",1);
builder.queryParam("b","abc");
builder.queryParam("c","x,y,z");
String path = builder.build().toUri().toString();
log.info("path: {}", path);
HttpEntity<String> httpEntity = new HttpEntity<>(headers);
ParameterizedTypeReference<RestDataResponse<UserInfo>> typeRef = new ParameterizedTypeReference<RestDataResponse<UserInfo>>() {};
ResponseEntity<RestDataResponse<UserInfo>> response = restTemplate.exchange(path,
HttpMethod.GET, httpEntity, typeRef);
if (response.getStatusCode() == HttpStatus.OK) {
// ....
}
}
2.2 RestTemplate POST请求示例代码
header参数的设置
requestBody参数的设置
response数据的解析
@Override
public boolean registerAccount1(String username, String password, String captcha) {
// 设置请求头
HttpHeaders headers = new HttpHeaders();
headers.add("Authorization", Base64Utils.createBasicHeader(appKey, appSecret));
log.info(" Authorization: {}", headers.get("Authorization").toString());
// 请求参数,一个list里面装着map
List<Map<String, Object>> list = new ArrayList<>();
Map<String, Object> departmentUserMap = new HashMap<>();
departmentUserMap.put("department", "[\"testDepartment\"]");
departmentUserMap.put("post", "管理员");
departmentUserMap.put("recursive", "true");
list.add(departmentUserMap);
// 封装http实体
HttpEntity<List<Map<String, Object>>> httpEntity = new HttpEntity<>(list, headers);
// 发送请求
ResponseEntity<Map> response = restTemplate.exchange(AccountConstants.URL_ACCOUNT_POST_REGISTER, HttpMethod.POST,
httpEntity, Map.class);
log.info("response body: {}", response.getBody());
return false;
}
@Override
public boolean registerAccount2(String username, String password, String captcha) {
// 设置请求头
HttpHeaders headers = new HttpHeaders();
headers.add("Authorization", Base64Utils.createBasicHeader(appKey, appSecret));
log.info(" Authorization: {}", headers.get("Authorization").toString());
// 请求参数,一个list里面装着map
Map<String, Object> registerMap = new HashMap<>();
registerMap.put("identity", username);
registerMap.put("password", password);
registerMap.put("captcha", captcha);
// 封装http实体
HttpEntity<Map<String, Object>> httpEntity = new HttpEntity<>(registerMap, headers);
ParameterizedTypeReference<RestDataResponse<RegisterResponse>> typeRef = new ParameterizedTypeReference<RestDataResponse<RegisterResponse>>() {
};
// 发送请求
ResponseEntity<RestDataResponse<RegisterResponse>> response = restTemplate.exchange(AccountConstants.URL_ACCOUNT_POST_REGISTER, HttpMethod.POST,
httpEntity, typeRef);
log.info("response body: {}", response.getBody());
return false;
}
2.3 RestTemplate Post 通过form提交数据,代码实例
/**
* oauth2 登录: 获取token+同时获取用户信息
* @param username
* @param password
* @return
*/
@Override
public OAuth2LoginResponse oauth2Login(String username, String password) {
// 设置请求头
HttpHeaders headers = new HttpHeaders();
headers.add("Authorization", Base64Utils.createBasicHeader(appKey, appSecret));
// headers.add("Content-type", "application/x-www-form-urlencoded");
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
// 封装参数,千万不要替换为Map与HashMap,否则参数无法传递
MultiValueMap<String, String> params= new LinkedMultiValueMap<String, String>();
params.add("grant_type", "password");
params.add("username", username);
params.add("password", password);
HttpEntity<MultiValueMap<String, String>> httpEntity = new HttpEntity<MultiValueMap<String, String>>(params, headers);
restTemplate.exchange(AccountConstants.URL_ACCOUNT_POST_OAUTH2_LOGIN, HttpMethod.POST, httpEntity, String.class);
ParameterizedTypeReference<RestDataResponse<OAuth2LoginResponse>> typeRef =
new ParameterizedTypeReference<RestDataResponse<OAuth2LoginResponse>>() {};
// 发送请求
ResponseEntity<RestDataResponse<OAuth2LoginResponse>> response = restTemplate.exchange(AccountConstants.URL_ACCOUNT_POST_OAUTH2_LOGIN,
HttpMethod.POST,
httpEntity, typeRef);
log.info("response body: {}", response.getBody());
if (response.getStatusCode() == HttpStatus.OK) {
RestDataResponse<OAuth2LoginResponse> body = response.getBody();
if (body != null && Objects.equals(body.getCode(), 0)) {
return body.getData();
}
String bodystr = JSON.toJSONString(body);
log.warn("rest response code:{}, message:{}, \r\n resp body:{}", body.getCode(), body.getMessage(), JSON.toJSONString(body));
log.error(" 登录接口调用失败: username:{}, password:{} ", username, password);
throw new ServiceException(body.getMessage());
}else {
log.error(" 登录接口调用失败: username:{}, password:{} ", username, password);
throw new ServiceException("登录接口调用失败");
}
}
二、RestTemplate 请求参数设置的几种方式
1. URL Path 中携带参数
不管是GET方法还是POST方法都可以通过这种方式,在url中携带参数
如: https://www.baidu.com?a=1&b=123&c=1,2,3
// response 返回值这里用了泛型
private void getDemo(){
// 设置请求头
HttpHeaders headers = new HttpHeaders();
headers.add("Authorization", "bearer " + accessToken);
// get请求构造url
UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(AccountConstants.URL_ACCOUNT_GET_USERINFO_BY_TOKEN);
builder.build("gg");
builder.queryParam("a",1);
builder.queryParam("b","abc");
builder.queryParam("c","x,y,z");
String path = builder.build().toUri().toString();
log.info("path: {}", path);
HttpEntity<String> httpEntity = new HttpEntity<>(headers);
ParameterizedTypeReference<RestDataResponse<UserInfo>> typeRef = new ParameterizedTypeReference<RestDataResponse<UserInfo>>() {};
ResponseEntity<RestDataResponse<UserInfo>> response = restTemplate.exchange(path,
HttpMethod.GET, httpEntity, typeRef);
if (response.getStatusCode() == HttpStatus.OK) {
// ....
}
}
2. ResponseBody中传递参数,JSON对象传递参数
ResponseBody中传递参数,服务端有个对象来接受这个参数,传输的是一个json对象
// 2. ResponseBody中传递参数,服务端有个对象来接受这个参数
private void fun1(){
// 设置请求头
HttpHeaders headers = new HttpHeaders();
headers.add("Authorization", Base64Utils.createBasicHeader(appKey, appSecret));
log.info(" Authorization: {}", headers.get("Authorization").toString());
Map<String, Object> registerMap = new HashMap<>();
registerMap.put("identity", username);
registerMap.put("password", password);
registerMap.put("captcha", captcha);
HttpEntity<Map<String, Object>> httpEntity = new HttpEntity<>(registerMap, headers);
ParameterizedTypeReference<RestDataResponse<RegisterResponse>> typeRef = new ParameterizedTypeReference<RestDataResponse<RegisterResponse>>() {};
// 发送请求
ResponseEntity<RestDataResponse<RegisterResponse>> response = restTemplate.exchange(AccountConstants.URL_ACCOUNT_POST_REGISTER,
HttpMethod.POST, httpEntity, typeRef);
}
// 服务端接受参数的对象是这样的:
@Data
public class RegisterRequest(){
private String username;
private String password;
private String captcha;
}
3. FORM 表单提交参数
form表单提交数据也非常常见,类似页面form提交数据的方式
// form 提交数据
private void fun2(){
// 设置请求头
HttpHeaders headers = new HttpHeaders();
headers.add("Authorization", Base64Utils.createBasicHeader(appKey, appSecret));
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
MultiValueMap<String, String> params= new LinkedMultiValueMap<String, String>();
params.add("token", accessToken);
params.add("time", "2023-08-22");
// 封装http实体
HttpEntity<MultiValueMap<String, String>> httpEntity = new HttpEntity<MultiValueMap<String, String>>(params, headers);
ParameterizedTypeReference<RestDataResponse<CheckTokenResponse>> typeRef =
new ParameterizedTypeReference<RestDataResponse<CheckTokenResponse>>() {};
// 发送请求
ResponseEntity<RestDataResponse<CheckTokenResponse>> response = restTemplate.exchange(AccountConstants.URL_ACCOUNT_POST_CHECK_TOKEN,
HttpMethod.POST,
httpEntity, typeRef);
if (response.getStatusCode() == HttpStatus.OK) {
//...
}
}