[英]Create a java REST client to call a spring boot REST API
我有一個僅使用POST JSON String的springboot項目,我正在使用gson將其轉換為HashMap。 我使用Postman作為POST進行了測試,並使用諸如{'fistname': 'John', 'lastname' : 'Doe'}
類的json字符串將主體添加為props
,轉換為props = {'fistname': 'John', 'lastname' : 'Doe'}
。 它按預期工作
@RequestMapping(value = "/rest", method = RequestMethod.POST)
protected String parse(@RequestParam("props") String props) {
Gson gson = new Gson();
Map<String, String> params = new HashMap<String, String>();
params = gson.fromJson(props, Map.class);
// Rest of the process
}
另一方面,我有一個JavaEE項目,需要調用此API
protected void callREST() {
try {
String json = someClass.getDate() //retrieved from database which is stored as json structure
Map<String, String> props = gson.fromJson(json, Map.class);
URL url = new URL("http://localhost:9090/myApp/rest");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
DataOutputStream wr = new DataOutputStream( conn.getOutputStream());
System.out.println(props.toString());
wr.writeBytes(json.toString());
wr.flush();
wr.close();
if(conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
throw new RuntimeException("Failed :: HTTP error code : " + conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String output;
System.out.println("Output from Server ... \n");
while((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
} catch(Exception e) {
//print stack trace
}
}
我收到Failed :: HTTP error code : 400
。 我懷疑spring boot在POST請求之后沒有收到props
變量中的數據。 我應該在客戶端代碼中添加些什么來傳遞道具和數據,以使調用成功?
注意:JavaEE在tomcat上運行:8080,Springboot在不同tomcat上運行:9090
@RequestParam
意味着服務器在請求URL http://localhost:9090/myApp/rest?param=.....
中等待參數,但是在您的客戶端中,您正在請求主體中編寫JSON。
嘗試在端點中使用@RequestBody
批注
protected String parse(@RequestBody String props) {...}
您的資源希望獲得表單參數(即,使用x-www-form-urlencoded編碼的鍵值對),其中值恰好是JSON(盡管您發布的內容不是有效的JSON)。
但是您的客戶端Java代碼將內容類型設置為application / json,然后將JSON作為正文發送,而不是將其作為x-www-form-urlencoded正文的鍵“ props”的值發送。
這樣就行不通了。
如果可以更改服務器,請執行此操作。 直接接受JSON作為正文:
@RequestMapping(value = "/rest", method = RequestMethod.POST)
public String parse(@RequestBody Map<String, String> map) {
...
}
如果不是,則需要發送正確的鍵值對,並確保該值已正確進行url編碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.