Java Spring HTTP 客户端
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22338176/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Spring HTTP Client
提问by marcelorocks
I am new to Spring and I need my Java app to connect to another API over HTTP (JSON, RESTful). Does the Spring Framework have anything like a JSON HTTP Rest Client? What do Spring developers usually use?
我是 Spring 的新手,我需要我的 Java 应用程序通过 HTTP(JSON、RESTful)连接到另一个 API。Spring 框架是否有类似 JSON HTTP Rest Client 的东西?Spring开发人员通常使用什么?
采纳答案by marcelorocks
I achieved what I needed with the following:
我通过以下方式实现了我所需要的:
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;
}
}
回答by Angular University
The simplest is to use the RestTemplate
, check this article on the official Spring blog:
最简单的就是使用RestTemplate
,查看Spring官方博客上的这篇文章:
The RestTemplate is the central Spring class for client-side HTTP access.
RestTemplate 是用于客户端 HTTP 访问的中央 Spring 类。
This is an example of a GET:
这是 GET 的示例:
String result = restTemplate.getForObject("http://example.com/hotels/{hotel}/bookings/{booking}", String.class, "42", "21");
回答by Piyush Mittal
i did it in following way :
我是通过以下方式做到的:
import java.io.FileReader;
import java.util.HashMap;
import java.util.Map;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.springframework.http.HttpEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
public class PostRequestMain {
/**
* POST with Headers call using Spring RestTemplate
*
*
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
MultiValueMap<String, String> headers = new LinkedMultiValueMap<String, String>();
Map map = new HashMap<String, String>();
map.put("Content-Type", "application/json");
headers.setAll(map);
Map req_payload = new HashMap();
req_payload.put("name", "piyush");
HttpEntity<?> request = new HttpEntity<>(req_payload, headers);
String url = "http://localhost:8080/portal-name/module-name/";
// Create a new RestTemplate instance
RestTemplate restTemplate = new RestTemplate();
// Add the String message converter
restTemplate.getMessageConverters().add(new StringHttpMessageConverter());
ResponseEntity<String> response = restTemplate.postForEntity(url, request, String.class);
System.out.println(response);
}
private static void getPayloadMap() {
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader("C:\Piyush\test.json"));
JSONObject jsonObject = (JSONObject) obj;
Map payLoadMap = new HashMap();
payLoadMap.putAll(jsonObject);
System.out.println(jsonObject);
} catch (Exception e) {
}
}
}