简体   繁体   English

使用 Spring Boot 对 REST API 的 GET/POST 请求

[英]GET/POST Requst to REST API using Spring Boot

I have a REST Service an external server like https://api.myrestservice.com and I have a Spring Boot Application running locally on http://localhost:8080 .我有一个 REST 服务,一个像https://api.myrestservice.com这样的外部服务器,我有一个在http://localhost:8080上本地运行的 Spring Boot 应用程序。 Now I want to make GET or POST request to the REST API address ie https://api.myrestservice.com/users to get all users, using my locally running Spring Boot App ie through http://localhost:8080/users .现在我想向 REST API 地址发出GETPOST请求,即https://api.myrestservice.com/users以获取所有用户,使用我本地运行的 Spring Boot 应用程序,即通过http://localhost:8080/users I am not getting how to redirect local app request to external server request.我不知道如何将本地应用程序请求重定向到外部服务器请求。

I hope I got your question right.我希望我答对了你的问题。 You are trying get your local app to get data from app running on your server.您正在尝试让您的本地应用程序从在您的服务器上运行的应用程序获取数据。

You can use the below sample code in your spring boot application.您可以在 Spring Boot 应用程序中使用以下示例代码。

 private void getUsers() { final String uri = "https://api.myrestservice.com/users"; RestTemplate restTemplate = new RestTemplate(); Users result = restTemplate.getForObject(uri, Users.class); System.out.println(result); }

Then your getUsers can be invoked by getUsers Controller in your spring boot app.然后你的 getUsers 可以在你的 Spring Boot 应用程序中被 getUsers 控制器调用。

I am adding the reference if you want to look at more examples - https://howtodoinjava.com/spring-restful/spring-restful-client-resttemplate-example/如果您想查看更多示例,我正在添加参考 - https://howtodoinjava.com/spring-restful/spring-restful-client-resttemplate-example/

Making post Api call from your code to another server:从您的代码到另一台服务器进行 post Api 调用:

suppose you have a server https://searchEmployee ... which returns you list of employees belonging to a particular city or belonging to a particular organization:假设您有一个服务器https://searchEmployee ... 它返回属于特定城市或属于特定组织的员工列表:

request body:请求正文:

{ 
"city" : "Ranchi",
"organisation" : "Bank Of America" 
}

json response: [{"name": "Vikash"},{"name":"kumar" },{}...etc] json 响应: [{"name": "Vikash"},{"name":"kumar" },{}...etc]

Then to make a post api call you can use RestTemplate in java like this:然后要进行后 api 调用,您可以像这样在 Java 中使用 RestTemplate:

public void makeApiCall(){ 
    final String uri = "https://searchEmployee...";

    RestTemplate restTemplate = new RestTemplate();

    String reqBody = "{"city": "Ranchi"}";
    String result = restTemplate.postForObject(uri, reqBody, String.class);

    // convert your result into json

    try {
                jsonResponse = new JSONObject(result);
        } catch (JSONException e) {
            e.printStackTrace();
        }
   //extract a value "name" from your json data:
   try{
    String value = jsonResponse.getString("name");  
    }catch(JSONException e) {
            e.printStackTrace();
        }
}

/********************************************************************/ /***************************************************** *******************/

if you have more than one request body parameters to set do it like this:如果您要设置多个请求正文参数,请执行以下操作:

String reqBody = "{\"quantity\":100,\"name\":\"product1\",\"ifBoolean\":false}";

false is a boolean value here in your request body and 100 is an integer. false 是请求正文中的布尔值,100 是整数。

NOTE if you are having problem in setting request body copy it directly from postman request body and paste it inside double quote.注意如果您在设置请求正文时遇到问题,请直接从邮递员请求正文中复制它并将其粘贴到双引号中。

There are many ways to do it.有很多方法可以做到。 Like Apache HTTP Components and other.像 Apache HTTP 组件等。 Sample样本

String type = "application/x-www-form-urlencoded" Or Set your desire content type;
String encodedData = URLEncoder.encode( rawData, "UTF-8" ); 
URL u = new URL("your remote url");
HttpURLConnection conn = (HttpURLConnection) u.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty( "Content-Type", type );
conn.setRequestProperty( "Content-Length", 
String.valueOf(encodedData.length()));
OutputStream os = conn.getOutputStream();
os.write(encodedData.getBytes());

There are a couple of thing going on here, Like URLEncoding is really mattered when came to security.这里发生了一些事情,比如 URLEncoding 在安全性方面真的很重要。 Note: Source of above code: here .注意:上述代码的来源: here

This is very Simple By using Java Clients you can Use RestTemplate or UniRest That one running on Remote is simply Producer and the one which is in local is Consumer So you can exchange method of Resttemplate or get method of Unirest Example Code is here.这很简单 通过使用 Java 客户端,您可以使用 RestTemplate 或 UniRest 在远程运行的只是生产者,而在本地运行的是消费者因此您可以交换 Resttemplate 的方法或 Unirest 示例代码的 get 方法在这里。

@RequestMapping(value = "/testclient")
    public String testclient()
    {
        HttpHeaders headers = new HttpHeaders();
        headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
        HttpEntity<String> entity = new HttpEntity<String>(headers);
        return restTemplate.exchange("https://www.mocky.io/v2/5185415ba171ea3a00704eed", HttpMethod.GET, entity, String.class).getBody();
}

For Unirest code is like this对于 Unirest 代码是这样的

HttpResponse<JsonNode> jsonResponse = null;
    try {
        jsonResponse = Unirest.get("https://www.mocky.io/v2/5185415ba171ea3a00704eed")
                .header("accept", "application/json").queryString("apiKey", "123").asJson();
    } catch (UnirestException e) { // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return jsonResponse.getBody().toString();

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM