我的 Web 服务使用另一个 Web 服务。 如何获取 json 格式响应并再次返回 json 格式。 听到的是我的代码: @ Controller @RequestMapping("/idx") 公共(public)类 HomeController {
@GetMapping("/{name}")
public @ResponseBody List<String> idx(@PathVariable String name) {
List<String> list = new ArrayList<String>();
try {
JSONParser parser = new JSONParser();
URL url = new URL("https://api.openweathermap.org/data/2.5/weather?q="+name+"&APPID=7dc66995a09d2c3db6e");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
if (conn.getResponseCode() != 200) {
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);
list.add(output);
}
conn.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return list;
}
最佳答案
我发现您正在使用spring框架,我建议您使用restTemplate来使用rest API。您可以获得如下 json 响应:
RestTemplate rest = new RestTemplate();
rest.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
JSONObject obj = rest.getForObject("https://api.openweathermap.org/data/2.5/weather?q=\"+name+\"&APPID=7dc66995a09d2c3db6e", JSONObject.class);
如果您想继续使用 HttpURLConnection
,您可以遵循此处的答案:
Parse JSON from HttpURLConnection object
关于java - 返回json格式的响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53821371/