RestTemplate常用请求

目录

一 基本配置

1 简单使用

2 处理中文乱码

3 发送https请求

二 GET

1 getForObject

(1) 不带参数

(2) 带参数-按顺序绑定( http://.../getData/{name}/{age})

(3) 带参数 (http://.../getData?name=xxx&age=xxx)

2 getForEntity

3 为URL设置编码

4 设置请求头

三 POST

1 postForObject

(1) application/x-www-form-urlencoded (无参)

(2) application/x-www-form-urlencoded (有参)

(3) JSON

2 postForEntity

3 带请求头

(1) application/x-www-form-urlencoded

(2) JSON

四 获取状态码非200的Body


一 基本配置

1 简单使用

@Bean
public RestTemplate restTemplate() {
  return new RestTemplate();
}
@Autowired
private RestTemplate restTemplate;

2 处理中文乱码

@Bean
public RestTemplate getRestTemplate(){
    RestTemplate restTemplate = new RestTemplate();
    //解决中文乱码
    restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
    return restTemplate;
}

3 发送https请求


@Bean
public RestTemplate restTemplate() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {

     TrustStrategy acceptingTrustStrategy = (X509Certificate[] chain, String authType) -> true;

     SSLContext sslContext = org.apache.http.ssl.SSLContexts.custom()
                .loadTrustMaterial(null, acceptingTrustStrategy)
                .build();

     SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext);

     CloseableHttpClient httpClient = HttpClients.custom()
                .setSSLSocketFactory(csf)
                .build();

     HttpComponentsClientHttpRequestFactory requestFactory =
                new HttpComponentsClientHttpRequestFactory();

     requestFactory.setHttpClient(httpClient);
     RestTemplate restTemplate = new RestTemplate(requestFactory);
     return restTemplate;
}

如果 org.apache.http 包没有引入下面这个依赖

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.5</version>
</dependency>

二 GET

1 getForObject

(1) 不带参数

服务端:

@GetMapping("/getData")
public Object getData() {
    return "收到数据";
}

客户端:

@GetMapping("/getData")
public Object getData() {
    String url = "http://localhost:8060/getData";
    return restTemplate.getForObject(url, String.class);
}

(2) 带参数-按顺序绑定( http://.../getData/{name}/{age})

服务端:

@GetMapping("/getData/{name}/{age}")
public Object getData(@PathVariable("name") String name,
                      @PathVariable("age") String age) {
    return "收到数据:name:"+name+", age:"+age;
}

客户端:

@GetMapping("/getData")
public Object getData() {
    String url = "http://localhost:8060/getData/{name}/{age}";
    return restTemplate.getForObject(url, String.class, "小东", "18");
}

@GetMapping("/getData")
public Object getData() {
    String url = "http://localhost:8060/getData/{name}/{age}";
    Map<String, Object> map = new HashMap<>();
    map.put("name", "小南");
    map.put("age", "18");
    return restTemplate.getForObject(url, String.class, map);
}

(3) 带参数 (http://.../getData?name=xxx&age=xxx)

服务端:

@GetMapping("/getData")
public Object getData(Student student) {
    return "收到数据:name:"+student.getName()+", age:"+student.getAge();
}

@Data
public class Student  {
    private String name;
    private String age;
}

@GetMapping("/getData")
public Object getData(String name, String age) {
    return "收到数据:name:"+name+", age:"+age;
}

客户端:

方式1: 使用UriComponentsBuilder

@GetMapping("/getData")
public Object getData() {
    String url = "http://localhost:8060/getData";
    UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
    builder.queryParam("name", "小南");
    builder.queryParam("age", "18");
    // 使用 builder.build().toUriString() 防止中文乱码。
    //如果直接builder.toUriString()会中文乱码
    return restTemplate.getForObject(builder.build().toUriString(), String.class);
}

@GetMapping("/getData")
public Object getData() {
    String url = "http://localhost:8060/getData";

    MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
    params.add("name", "小小");
    params.add("age", "18");

    UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
    builder.queryParams(params);
    // 使用 builder.build().toUriString() 防止中文乱码。
    // 如果直接builder.toUriString()会中文乱码
    return restTemplate.getForObject(builder.build().toUriString(), String.class);
}

方式2: 直接拼接到URL

@GetMapping("/getData")
public Object getData() {
    String url = "http://localhost:8060/getData?name=小西&age=18";
    return restTemplate.getForObject(url, String.class);
}

方式3: 使用占位符

@GetMapping("/getData")
public Object getData() {
    String url = "http://localhost:8060/getData?name={name}&age={age}";
    Map<String, String> map = new HashMap<>();
    map.put("name", "小南");
    map.put("age", "18");
    return restTemplate.getForObject(url, String.class, map);
}

@GetMapping("/getData")
public Object getData() {
    String url = "http://localhost:8060/getData?name={name}&age={age}";
    return restTemplate.getForObject(url, String.class, "小红", "21");
}

2 getForEntity

调用和 getForObject类似, 但可以从getForEntiy获取更多的响应数据

客户端:

@GetMapping("/getData")
public Object getData() {
    String url = "http://localhost:8060/getData?name={name}&age={age}";
    ResponseEntity<String> entity = restTemplate.getForEntity(url, String.class, "小男", "18");
    HttpStatus statusCode = entity.getStatusCode();
    String body = entity.getBody();
    int statusCodeValue = entity.getStatusCodeValue();
    HttpHeaders headers = entity.getHeaders();
    return "statusCode:"+statusCode+", statusCodeValue:"+statusCodeValue+", body"+body+" , headers:"+headers;
}

3 为URL设置编码

客户端:

@GetMapping("/getData")
public Object getData() throws UnsupportedEncodingException {
    String url = "http://localhost:8060/getData";

    MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
    params.add("name", "小小");
    params.add("age", "18");

    UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
    builder.queryParams(params);

    // builder.toUriString()会中文乱码
    // 可以使用 URLDecoder 对其进行编码
    String decode = URLDecoder.decode(builder.toUriString(), "utf-8");

    return restTemplate.getForObject(decode, String.class);
}

4 设置请求头

使用 exchange 方法发送get请求

服务端:

@GetMapping("/getData")
public Object getData(HttpServletRequest request, String name, String age) {
    String token = request.getHeader("token");
    return "收到数据:token: +"+token+" ,name:"+name+", age:"+age;
}

客户端:

@GetMapping("/getData")
public Object getData() throws UnsupportedEncodingException {
    String url = "http://localhost:8060/getData?name={name}&age={age}";

    HttpHeaders headers = new HttpHeaders();
    headers.add("token","123456");

    HttpEntity request = new HttpEntity<>(headers);

    return restTemplate.exchange(url, HttpMethod.GET, request, String.class, "小男", "18");
}

三 POST

1 postForObject

(1) application/x-www-form-urlencoded (无参)

服务端:

@PostMapping("/getData")
public Object getData() {
    return "收到数据";
}

客户端:

String url = "http://localhost:8060/getData";
restTemplate.postForObject(url, null, String.class);

(2) application/x-www-form-urlencoded (有参)

服务端:

@PostMapping("/getData")
public Object getData(Student student) {
    return  "收到数据:name:"+student.getName()+", age:"+student.getAge();
}

客户端:

String url = "http://localhost:8060/getData";

MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
map.add("name", "小明");
map.add("age", "20");

restTemplate.postForObject(url, map, String.class);

(3) JSON

服务端:

@PostMapping("/getData")
public Object getData(@RequestBody Student student) {
    return  "收到数据:name:"+student.getName()+", age:"+student.getAge();
}

客户端:

String url = "http://localhost:8060/getData";

Student student = new Student();
student.setName("小明");
student.setAge(5);

restTemplate.postForObject(url, student, String.class);

String url = "http://localhost:8060/getData";

Map<String, Object> map = new HashMap<>();
map.put("name", "小红");
map.put("age", "18");

restTemplate.postForObject(url, map, String.class);

2 postForEntity

和 postForObject类似

3 带请求头

(1) application/x-www-form-urlencoded

服务端:

@PostMapping("/getData")
public Object getData(HttpServletRequest request, Student student) {
    String token = request.getHeader("token");
    return  "收到数据:token: "+token+", name:"+student.getName()+", age:"+student.getAge();
}

客户端:

String url = "http://localhost:8060/getData";
// 请求参数
MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
map.add("name", "小明");
map.add("age", "20");
// 请求头
HttpHeaders headers = new HttpHeaders();
headers.add("token", "1234");
// 将请求头放到 HttpEntity中
HttpEntity httpEntity = new HttpEntity<>(map,headers);
// 发送请求
restTemplate.postForObject(url, httpEntity, String.class);

String url = "http://localhost:8060/getData";
// 请求参数
MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
map.add("name", "小明");
map.add("age", "20");
// 组装url 和 请求参数
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
builder.queryParams(map);
// 请求头
HttpHeaders headers = new HttpHeaders();
headers.add("token", "1234");
// 将请求头放到 HttpEntity中
HttpEntity<HttpHeaders> httpEntity = new HttpEntity<>(headers);
// 发送请求
restTemplate.postForObject(builder.build().toUriString(), httpEntity, String.class);

(2) JSON

服务端:

@PostMapping("/getData")
public Object getData(HttpServletRequest request,@RequestBody Student student) {
    String token = request.getHeader("token");
    return  "收到数据:token: "+token+", name:"+student.getName()+", age:"+student.getAge();
}

客户端:

String url = "http://localhost:8060/getData";
// 请求参数
Student student = new Student();
student.setName("小欧");
student.setAge(5);
// 请求头
HttpHeaders headers = new HttpHeaders();
headers.add("token", "1234");
// 将请求头放到 HttpEntity中
HttpEntity httpEntity = new HttpEntity<>(student, headers);
// 发送请求
return restTemplate.postForObject(url, httpEntity, String.class);

String url = "http://localhost:8060/getData";

// 请求参数
Map<String, String> map = new HashMap<>();
map.put("name", "小明");
map.put("age", "20");
// 请求头
HttpHeaders headers = new HttpHeaders();
headers.add("token", "1234");
// 将请求头放到 HttpEntity中
HttpEntity httpEntity = new HttpEntity<>(map,headers);
// 发送请求
restTemplate.postForObject(url, httpEntity, String.class);

四 获取状态码非200的Body

        restTemplate调用时,当响应的状态码非200 (401,500等)均会以异常的形式抛出。 可通过 HttpClientErrorException 获取body。

服务端:

// 响应的状态码设置为400
@ResponseStatus(value = HttpStatus.BAD_REQUEST)
@GetMapping("/getData")
public Object getData() {
    return  "接口异常了";
}

客户端:

String url = "http://localhost:8060/getData";
// 转态码
int code = 0;
// body
String body = "";
try {
    ResponseEntity<String> result = restTemplate.getForEntity(url, String.class);
} catch (HttpClientErrorException e) {
    code = e.getStatusCode().value();
    body = e.getResponseBodyAsString();
}

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值