返回json格式的响应

时间:2018-12-17 18:50:56

标签: java json spring

我有使用其他Web服务的Web服务。 我如何获取json格式响应并再次返回json格式。 听到是我的代码:     @Controller     @RequestMapping(“ / idx”)     公共类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;


    }

1 个答案:

答案 0 :(得分:1)

我看到您正在使用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