简体   繁体   English

Destination Weather API for REST API not returning JSON data in postman

[英]Destination Weather API for REST API not returning JSON data in postman

I am Creating a REST API in java and testing it in postman and in the database have the latitude and longitude, I am trying to use the OpenWeather API to return weather data based on the latitude and longitude. I am Creating a REST API in java and testing it in postman and in the database have the latitude and longitude, I am trying to use the OpenWeather API to return weather data based on the latitude and longitude. however, when testing it in postman it is returning an HTML and not the JSON data I requested.但是,在 postman 中对其进行测试时,它返回的是 HTML 而不是我请求的 JSON 数据。

the path I am trying to test is我要测试的路径是

http://localhost:8080/Assignment2C/map/weather/4

the code in my controller is我的 controller 中的代码是

  @GetMapping(value = "weather/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
    public String getWeather(@PathVariable("id") int id) {
        BreweriesGeocode geocode = geocode_service.getGeocode(id);
        Breweries brewerie = breweries_service.getBrewerieById(id);

        double latitude = geocode.getLatitude();
        double longitude = geocode.getLongitude();
       String output = "https://api.openweathermap.org/data/2.5/weather?lat=" + latitude + "&lon=" + longitude + "&appid=4a1f5501b2798f409961c62d384a1c74";
       return output;

when using Postman it returns this当使用 Postman 它返回这个

https: //api.openweathermap.org/data/2.5/weather?lat=59.74509811401367&lon=10.213500022888184&appid=4a1f5501b2798f409961c62d384a1c74

but when I test the path that postman produces in the browser但是当我测试 postman 在浏览器中生成的路径时

https://api.openweathermap.org/data/2.5/weather?lat=59.74509811401367&lon=10.213500022888184&appid=4a1f5501b2798f409961c62d384a1c74

it returns the correct JSON data它返回正确的 JSON 数据

which is这是

{"coord":{"lon":10.21,"lat":59.75},"weather":[{"id":800,"main":"Clear","description":"clear sky","icon":"01d"}],"base":"stations","main":{"temp":291.36,"feels_like":289.49,"temp_min":288.71,"temp_max":294.26,"pressure":1028,"humidity":40},"wind":{"speed":0.89,"deg":190},"clouds":{"all":1},"dt":1587551663,"sys":{"type":3,"id":2006615,"country":"NO","sunrise":1587526916,"sunset":1587581574},"timezone":7200,"id":6453372,"name":"Drammen","cod":200}

how do I get the JSON data to appear in postman when I test it?测试时如何让 JSON 数据出现在 postman 中?

I tested the URL in postman, it returns the correct response.我在 postman 中测试了 URL,它返回了正确的响应。 Check the below screen maybe you're doing something different.检查下面的屏幕,也许你正在做一些不同的事情。 邮递员回应

Make sure there are no spaces in url, i see the url you used in Postman had space after the ":"确保 url 中没有空格,我看到您在 Postman 中使用的 url 在“:”之后有空格

The Postman is parsing/showing the correct value, as you are sending the url in the response. Postman 正在解析/显示正确的值,因为您在响应中发送 url。

To call an API within your code you need to use a HTTP Client/Handler.要在您的代码中调用 API,您需要使用 HTTP 客户端/处理程序。 If you just assign the URL to a variable it will simply store it as a string and it is never going to call given url.如果您只是将 URL 分配给一个变量,它将简单地将其存储为一个字符串,并且在给定 url 的情况下它永远不会调用。

RestTemplate class (available by default in Spring, no other dependency required) is a simple HTTP client which allows to make API calls from within your code. RestTemplate class (available by default in Spring, no other dependency required) is a simple HTTP client which allows to make API calls from within your code.
You can use RestTemplate to call the OpenWeather API and get the JSON response, the same response can be returned and viewed in Postman.可以使用RestTemplate调用OpenWeather API得到JSON响应,同样的响应可以在Postman中返回查看。


If you are sure that you are going to make only HTTP calls and no HTTPS, then follow approach 1 otherwise follow approach 2 -如果您确定只进行 HTTP 调用而不进行 HTTPS,则遵循方法 1,否则遵循方法 2 -

Approach 1:方法一:

@RestController
public class WeatherController{

    @Autowired
    RestTemplate restTemplate;

    @GetMapping(value = "weather/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
    public String getWeather(@PathVariable("id") int id) {
        BreweriesGeocode geocode = geocode_service.getGeocode(id);
        Breweries brewerie = breweries_service.getBrewerieById(id);

        double latitude = geocode.getLatitude();
        double longitude = geocode.getLongitude();
        String url = "http://api.openweathermap.org/data/2.5/weather?lat="+latitude+"&lon="+longitude+"&appid=4a1f5501b2798f409961c62d384a1c74";

        //Calling OpenWeather API
        ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);
        String output = response.getBody();
        return output;
    }
}

Approach 2:方法二:

import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;

import javax.net.ssl.SSLContext;

import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

@Component
public class CustomRestTemplate {

    /**
     * @param isHttpsRequired - pass true if you need to call a https url, otherwise pass false
     */
    public RestTemplate getRestTemplate(boolean isHttpsRequired)
            throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException {

        // if https is not required,
        if (!isHttpsRequired) {
            return new RestTemplate();
        }

        // else below code adds key ignoring logic for https calls
        TrustStrategy acceptingTrustStrategy = (X509Certificate[] chain, String authType) -> true;
        SSLContext sslContext = org.apache.http.ssl.SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy)
                .build();

        SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext);

        CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(csf).build();

        HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
        requestFactory.setHttpClient(httpClient);

        RestTemplate restTemplate = new RestTemplate(requestFactory);       
        return restTemplate;
    }
}

Then in the controller class you can do as below-然后在 controller class 你可以做如下 -

@RestController
public class WeatherController{


    @Autowired
    CustomRestTemplate customRestTemplate;

    @GetMapping(value = "weather/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
    public String getWeather(@PathVariable("id") int id) {
        BreweriesGeocode geocode = geocode_service.getGeocode(id);
        Breweries brewerie = breweries_service.getBrewerieById(id);

        double latitude = geocode.getLatitude();
        double longitude = geocode.getLongitude();
        String url = "https://api.openweathermap.org/data/2.5/weather?lat="+latitude+"&lon="+longitude+"&appid=4a1f5501b2798f409961c62d384a1c74";

        // Getting instance of Rest Template
        // Passing true becuase the url is a HTTPS url
        RestTemplate restTemplate = customRestTemplate.getRestTemplate(true);

        //Calling OpenWeather API
        ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);

        String output = response.getBody();

        return output;
    }
}

You can write a Http Error Handler for the RestTemplate reponses if reponse code is not a success code.如果响应代码不是成功代码,您可以为 RestTemplate 响应编写 Http 错误处理程序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM