gpt4 book ai didi

java - Spring HTTP 客户端

转载 作者:IT老高 更新时间:2023-10-28 13:04:57 25 4
gpt4 key购买 nike

我是 Spring 新手,我需要我的 Java 应用程序通过 HTTP(JSON、RESTful)连接到另一个 API。 Spring 框架是否有类似 JSON HTTP Rest Client 的东西? Spring 开发者通常使用什么?

最佳答案

我通过以下方式实现了我所需要的:

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

public class RestClient {

private String server = "http://localhost:3000";
private RestTemplate rest;
private HttpHeaders headers;
private HttpStatus status;

public RestClient() {
this.rest = new RestTemplate();
this.headers = new HttpHeaders();
headers.add("Content-Type", "application/json");
headers.add("Accept", "*/*");
}

public String get(String uri) {
HttpEntity<String> requestEntity = new HttpEntity<String>("", headers);
ResponseEntity<String> responseEntity = rest.exchange(server + uri, HttpMethod.GET, requestEntity, String.class);
this.setStatus(responseEntity.getStatusCode());
return responseEntity.getBody();
}

public String post(String uri, String json) {
HttpEntity<String> requestEntity = new HttpEntity<String>(json, headers);
ResponseEntity<String> responseEntity = rest.exchange(server + uri, HttpMethod.POST, requestEntity, String.class);
this.setStatus(responseEntity.getStatusCode());
return responseEntity.getBody();
}

public void put(String uri, String json) {
HttpEntity<String> requestEntity = new HttpEntity<String>(json, headers);
ResponseEntity<String> responseEntity = rest.exchange(server + uri, HttpMethod.PUT, requestEntity, null);
this.setStatus(responseEntity.getStatusCode());
}

public void delete(String uri) {
HttpEntity<String> requestEntity = new HttpEntity<String>("", headers);
ResponseEntity<String> responseEntity = rest.exchange(server + uri, HttpMethod.DELETE, requestEntity, null);
this.setStatus(responseEntity.getStatusCode());
}

public HttpStatus getStatus() {
return status;
}

public void setStatus(HttpStatus status) {
this.status = status;
}
}

关于java - Spring HTTP 客户端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22338176/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com