GET/POST Requst to REST API using Spring Boot



我有一个REST服务,像https://api.myrestservice.com这样的外部服务器,我有一个在http://localhost:8080本地运行的Spring Boot应用程序。现在我想向 REST API 地址发出GETPOST请求,即https://api.myrestservice.com/users使用我本地运行的 Spring 启动应用程序(即通过http://localhost:8080/users(获取所有用户。我不知道如何将本地应用程序请求重定向到外部服务器请求。

我希望我答对了你的问题。您正在尝试让本地应用程序从服务器上运行的应用程序获取数据。

您可以在 Spring 引导应用程序中使用以下示例代码。

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

然后,可以在 Spring 启动应用程序中由 getUsers Controller 调用 getUsers。

如果您想查看更多示例,我将添加参考 - https://howtodoinjava.com/spring-restful/spring-restful-client-resttemplate-example/

从您的代码向另一台服务器进行 API 调用:

假设您有一个服务器 https://searchEmployee...这将返回属于特定城市或属于特定组织的员工列表:

请求正文:

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

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

然后要进行 post 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();
}
}

/****

如果要设置多个请求正文参数,请执行以下操作:

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

false 是请求正文中的布尔值,100 是整数。

注意,如果您在设置请求正文时遇到问题,请直接从邮递员请求正文复制它并将其粘贴在双引号内。

有很多方法可以做到这一点。比如Apache HTTP Components等。样本

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

这里有几件事发生,比如 URLEncoding 在安全性方面真的很重要。 注意:以上代码的来源:这里。

这很简单 通过使用Java客户端,您可以使用RestTemplate或UniRest 在远程上运行的那个只是生产者,而在本地运行的那个是消费者,所以你可以交换 Resttemplate 的方法或获取 Unirest 的方法 示例代码在这里。

@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();
}

对于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();

最新更新