0
我輸入的是URL和請求負載。Java RESTful webservice-POST帶有有效負載
說, 網址:https://somesresource.com
有效載荷:{用戶名: 「4566」}
我回來的輸出是一個JSON與幾個鍵值對。
我試着在Rest Console中做這個,輸出(Json)看起來不錯。但是,當我嘗試運行下面的程序時,輸出不是json,而是來自URL服務器的文件(html我想)。我如何檢索Json而不是文件?
@Transactional
@RequestMapping(value = "/xxx", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody
String consumer() throws Exception {
String line;
String userId = "12345";
StringBuffer jsonString = new StringBuffer();
URL url = new URL("https://somewebsite/userprofile");
String payload="{\"userId\":\""+sid+"\"}";
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
try {
OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
writer.write(payload);
writer.close();
System.out.print(connection.getInputStream().toString());
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
while ((line = br.readLine()) != null) {
jsonString.append(line);
}
br.close();
connection.disconnect();
}
catch(Exception e) {
}
return jsonString.toString();
}