語境
我有兩個控制器:/testParams與/callTestParams
控制器/testParams接收型實施例的一個目的,我可以呼叫從郵差該控制器沒有任何問題。
控制器使用RestTemplate在內部/callTestParams呼叫,但回應是 500 Internal Server Error。我假設 的實作相當于 Postman 的呼叫。/testParams/callTestParams
這是代碼:
@RequestMapping(value = "/testParams",
method = RequestMethod.POST, produces = "application/json", consumes = "application/json")
public ResponseEntity<Object> testParams(
@RequestBody Example credentials
) {
JSONObject params = new JSONObject( credentials );
System.out.println( params.get("clientId") " from JSONObject");
System.out.println( credentials.getClientId() " from GraphCredentials");
return new ResponseEntity<>(credentials,HttpStatus.OK);
}
@RequestMapping(value = "/callTestParams",
method = RequestMethod.POST, produces = "application/json", consumes = "application/json")
public ResponseEntity<Object> callTestParams() {
String url = "http://localhost:8080/GraphClient/testParams";
HttpHeaders headers = new HttpHeaders();
headers.set( HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE );
JSONObject params = new JSONObject();
params.put("clientId", "value1" );
RestTemplate restTemplate = new RestTemplate();
HttpEntity<?> entity = new HttpEntity<>(params,headers);
HttpEntity<Object> response = restTemplate.exchange(
url,
HttpMethod.POST,
entity,
Object.class
);
return new ResponseEntity<>(response.getBody(), HttpStatus.OK);
}
這是 Postman 對 /testParams 的回復
標頭:( 內容型別,應用程式/json)
請求 正文: JSON(應用程式/json)
{"clientId":"value1"}
回復:
{
"clientId": "value1",
"clientSecret": null,
"tenantId": null,
"scope": null,
"grantType": null,
"microsoftLoginBaseURL": "https://login.microsoftonline.com/"
}
這是 Postman 對 /callTestParams 的回復
{
"timestamp": "2022-01-09T03:39:06.878 0000",
"status": 500,
"error": "Internal Server Error",
"message": "500 Internal Server Error",
"path": "/GraphClient/callTestParams"
}
這是控制臺中的錯誤>
由于例外 [JSONObject["clientId"] not found.],從請求 [/testParams] 轉發到錯誤頁面。]: org.json.JSONException: JSONObject["clientId"] 未找到。

uj5u.com熱心網友回復:
在 HttpEntity 建構式的主體引數中,您需要將引數作為字串傳遞
HttpEntity<?> entity = new HttpEntity<>(params.toString(),headers);
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/409934.html
標籤:
