我输入的是URL和请求有效负载。
说,
网址:https://somesresource.com
有效负载:{userId:" 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();
}
答案 0 :(得分:0)
我认为您在应用程序中缺少转换器。我在Spring中使用RestFul Web服务并使用MappingJacksonHttpMessageConverter来实现&来自JSON的转换。如果您正在寻找特定答案,请提供有关配置的更多详细信息。