Reputation: 99
I have web service that use another web service. How can i get json format response and return json format again. Hear is my code : @Controller @RequestMapping("/idx") public class 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;
}
Upvotes: 0
Views: 246
Reputation: 2119
I see that you are using spring framework, I would recommend you to use restTemplate to consume rest APIs. You can get json response like below:
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);
If you want to continue using HttpURLConnection
there's an answer here that you can follow:
Parse JSON from HttpURLConnection object
Upvotes: 1