java调用第三方接口RestTemplate
时间: 2023-10-04 13:04:27 浏览: 150
Java中可以使用RestTemplate来调用第三方接口。下面是一个简单的示例代码:
```java
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
public class RestTemplateExample {
public static void main(String[] args) {
RestTemplate restTemplate = new RestTemplate();
// 设置请求头
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
// 可以设置其他请求头参数
// 构建请求实体
HttpEntity<String> requestEntity = new HttpEntity<>(headers);
// 发送GET请求
ResponseEntity<String> responseEntity = restTemplate.exchange("http://api.example.com/endpoint", HttpMethod.GET, requestEntity, String.class);
// 获取响应结果
String response = responseEntity.getBody();
System.out.println(response);
}
}
```
在上面的示例中,我们首先创建了一个RestTemplate对象。然后,我们设置了请求头参数,例如Content-Type。接下来,我们构建了一个HttpEntity对象,将请求头信息和请求体(如果有)传递给RestTemplate的exchange方法。最后,我们可以通过responseEntity对象获取响应结果。
你需要根据自己的需求来设置请求方法(如GET、POST等)、URL、请求头参数、请求体内容等。另外,你还可以根据具体的接口返回类型来调整exchange方法的第四个参数类型。
希望这个简单示例对你有所帮助!
阅读全文
相关推荐


















