[英]GET/POST Requst to REST API using Spring Boot
我有一个 REST 服务,一个像https://api.myrestservice.com
这样的外部服务器,我有一个在http://localhost:8080
上本地运行的 Spring Boot 应用程序。 现在我想向 REST API 地址发出GET或POST请求,即https://api.myrestservice.com/users
以获取所有用户,使用我本地运行的 Spring Boot 应用程序,即通过http://localhost:8080/users
。 我不知道如何将本地应用程序请求重定向到外部服务器请求。
我希望我答对了你的问题。 您正在尝试让您的本地应用程序从在您的服务器上运行的应用程序获取数据。
您可以在 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); }
然后你的 getUsers 可以在你的 Spring Boot 应用程序中被 getUsers 控制器调用。
如果您想查看更多示例,我正在添加参考 - https://howtodoinjava.com/spring-restful/spring-restful-client-resttemplate-example/
从您的代码到另一台服务器进行 post Api 调用:
假设您有一个服务器https://searchEmployee ... 它返回属于特定城市或属于特定组织的员工列表:
请求正文:
{
"city" : "Ranchi",
"organisation" : "Bank Of America"
}
json 响应: [{"name": "Vikash"},{"name":"kumar" },{}...etc]
然后要进行后 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 组件等。 样本
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 在安全性方面真的很重要。 注意:上述代码的来源: 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();
}
对于 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.