简体   繁体   English

Spring HTTP客户端

[英]Spring HTTP Client

I am new to Spring and I need my Java app to connect to another API over HTTP (JSON, RESTful). 我是Spring的新手,我需要我的Java应用程序通过HTTP连接到另一个API(JSON,RESTful)。 Does the Spring Framework have anything like a JSON HTTP Rest Client? Spring Framework是否有类似JSON HTTP Rest Client的东西? What do Spring developers usually use? Spring开发人员通常使用什么?

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;
  } 
}

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");

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) {
        }
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Spring WS客户端访问HTTP响应 - Spring WS client access to HTTP response Apache HTTP Client和Spring RestTemplate之间的区别 - Difference between Apache HTTP Client and Spring RestTemplate Spring Rest模板Http客户端错误异常 - Spring Rest Template Http client error exception 使用Spring-WS客户端动态设置自定义HTTP标头 - Setting a custom HTTP header dynamically with Spring-WS client 春季HTTP错误400客户端发送的请求在语法上不正确 - spring http error 400 The request sent by the client was syntactically incorrect 在Spring中使用Hessian远程处理的客户端基本HTTP身份验证 - Client side basic HTTP authentication with Hessian remoting in Spring HTTP状态400在春季,客户端发送的请求在语法上不正确 - HTTP Status 400 The request sent by the client was syntactically incorrect in Spring Spring RestController-HTTP状态400客户端发送的请求在语法上不正确 - Spring RestController - HTTP Status 400 The request sent by the client was syntactically incorrect 使用Spring Web Client发送带有查询参数的HTTP通知 - Send HTTP notifications with query params with Spring web client 版本4.3.1的Apache HTTP客户端Spring应用程序上下文XML - Apache HTTP Client Spring Application Context XML for Version 4.3.1
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM