[英]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.