首页 > 其他分享 >RestTemplate发送带参数和头的GET请求

RestTemplate发送带参数和头的GET请求

时间:2022-11-09 10:55:12浏览次数:64  
标签:String GET url RestTemplate request 发送 headers

本文译自:https://attacomsian.com/blog/spring-boot-resttemplate-get-request-parameters-headers
在本文中,你将学会在Spring Boot应用中使用RestTemplate类发送不同的HTTP GET请求。

简单GET请求

发送GET HTTP请求,可以使用getForObject()getForEntity()方法。
如下示例,使用getForObject()方法获取JSON字符串形式的用户信息:

// request url
String url = "https://jsonplaceholder.typicode.com/posts/1";

// create an instance of RestTemplate
RestTemplate restTemplate = new RestTemplate();

// make an HTTP GET request
String json = restTemplate.getForObject(url, String.class);

// print json
System.out.println(json);

带参数的GET请求

发送请求参数时,可以把参数直接追加到URL尾部,或者使用占位符。
示例如下,将请求参数追加到URL尾部的GET请求:

// request url
String url = "https://google.com/search?q=java";

// create an instance of RestTemplate
RestTemplate restTemplate = new RestTemplate();

// make an HTTP GET request
String html = restTemplate.getForObject(url, String.class);

相似的,在URL里增加占位符的方式携带请求参数:

// request url
String url = "https://google.com/search?q={q}";

// create an instance of RestTemplate
RestTemplate restTemplate = new RestTemplate();

// make an HTTP GET request
String html = restTemplate.getForObject(url, String.class, "java");

带参数和头的GET请求

在HTTP GET请求中携带自定义的请求头,应该使用RestTemplate类提供的通用的exchange()方法。
如下GET请求携带了请求参数和请求头:

// request url
String url = "https://jsonplaceholder.typicode.com/posts/{id}";

// create an instance of RestTemplate
RestTemplate restTemplate = new RestTemplate();

// create headers
HttpHeaders headers = new HttpHeaders();

// set `Content-Type` and `Accept` headers
headers.setContentType(MediaType.APPLICATION_JSON);
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));

// example of custom header
headers.set("X-Request-Source", "Desktop");

// build the request
HttpEntity request = new HttpEntity(headers);

// make an HTTP GET request with headers
ResponseEntity<String> response = restTemplate.exchange(
        url,
        HttpMethod.GET,
        request,
        String.class,
        1
);

// check response
if (response.getStatusCode() == HttpStatus.OK) {
    System.out.println("Request Successful.");
    System.out.println(response.getBody());
} else {
    System.out.println("Request Failed");
    System.out.println(response.getStatusCode());
}

使用Basic Authentication的GET请求

如下示例,在RestTemplate GET请求中携带basic authentication。

// request url
String url = "https://jsonplaceholder.typicode.com/posts";

// create an instance of RestTemplate
RestTemplate restTemplate = new RestTemplate();

// create headers
HttpHeaders headers = new HttpHeaders();

// add basic authentication header
headers.setBasicAuth("username", "password");

// build the request
HttpEntity request = new HttpEntity(headers);

// make an HTTP GET request with headers
ResponseEntity<String> response = restTemplate.exchange(
        url,
        HttpMethod.GET,
        request,
        String.class
);

// check response
if (response.getStatusCode() == HttpStatus.OK) {
    System.out.println("Request Successful.");
    System.out.println(response.getBody());
} else {
    System.out.println("Request Failed");
    System.out.println(response.getStatusCode());
}

将响应映射到Java对象的GET请求

使用RestTemplate,可以将JSON形式的响应直接映射为Java对象。首先创建一个简单的实体类:
Post.java

public class Post implements Serializable {

    private int userId;
    private int id;
    private String title;
    private String body;

    public Post() {
    }

    public Post(int userId, int id, String title, String body) {
        this.userId = userId;
        this.id = id;
        this.title = title;
        this.body = body;
    }

    // getters and setters, equals(), toString() .... (omitted for brevity)
}

现在,exchange()方法可以使用Post类作为响应类型了。

// request url
String url = "https://jsonplaceholder.typicode.com/posts/1";

// create an instance of RestTemplate
RestTemplate restTemplate = new RestTemplate();

// create headers
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));

// build the request
HttpEntity request = new HttpEntity(headers);

// make an HTTP GET request with headers
ResponseEntity<Post> response = restTemplate.exchange(
        url,
        HttpMethod.GET,
        request,
        Post.class
);

// check response
if (response.getStatusCode() == HttpStatus.OK) {
    System.out.println("Request Successful.");
    System.out.println(response.getBody());
} else {
    System.out.println("Request Failed");
    System.out.println(response.getStatusCode());
}

标签:String,GET,url,RestTemplate,request,发送,headers
From: https://www.cnblogs.com/windyWu/p/16872871.html

相关文章

  • python get请求传array数组
    前言使用传统的http发get请求时,如果传参为array数组,参数名称为a时,可以这样传值a=1&a=2&a=3,但是当只有一个时,这种方式就不合理了。get请求还有另外一种方式传array数组,在......
  • C#的GET/SET
     //类publicclassPerson{//字段privatestringname;  privateintage;  privatestringsex;//属性publicstringName{get{returnname;}se......
  • RestTemplateUtils 转发工具类
    @ComponentpublicclassRestTemplateUtils{@AutowiredprivateRestTemplaterestTemplate;privatestaticRestTemplateUtilsrtu;@PostConstr......
  • android-code-getip
    publicStringgetIP(){try{for(Enumeration<NetworkInterface>en=NetworkInterface.getNetworkInterfaces();en.hasMoreElements();){......
  • QTableWidget 遍历
    for(introw=0;row<ui->tableWidget->rowCount();row++){ for(intcol=0;col<ui->tableWidget->columnCount();col++) { QTableWidgetItem*item=ui->tableWidg......
  • Installing wxWidgets-3.2.1 on CentOS 8.3
    一、InstallingwxWidgets-3.2.1onCentOS8.3地址https://www.wxwidgets.org 安装依赖dnfinstall-ybzip2gtk2-develbinutils-develwget下载cd/opt/soft......
  • git submodule add 报错SSL certificate problem unable to get local issuer certifi
    在使用hugo并安装主题时遇到的错误SSLcertificateproblem:unabletogetlocalissuercertificate(base)PSE:\vscodeProject\chz8bit.github.io\quickstart>gitsu......
  • xp下GetLastError实现
      大家对这个win32API一定很熟悉了,那就来看下他的实现:0:001>x*!GetLastError//搜索符号地址7c830759kernel32!GetLastError=<notypeinformation>0:001>uf7......
  • HM-RocketMQ1.4【RocketMQ消息发送样例】
    0初始项目<dependency><groupId>org.apache.rocketmq</groupId><artifactId>rocketmq-client</artifactId><version>4.4.0</version></dependency>消......
  • getCurrentPages()的使用
    getCurrentPages()函数用于获取当前页面栈的实例,以数组形式按栈的顺序给出,第一个元素为首页,最后一个元素为当前页面。注意:不要尝试修改页面栈,会导致路由以及页面状态错......