【问题标题】:return json format response返回 json 格式响应
【发布时间】:2019-05-18 04:23:20
【问题描述】:

我有使用另一个 Web 服务的 Web 服务。 如何获得 json 格式响应并再次返回 json 格式。 听到是我的代码: @控制器 @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;


    }

【问题讨论】:

标签: java json spring


【解决方案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

【讨论】:

  • 谢谢我的朋友
猜你喜欢
  • 2013-03-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多