springboot 采用HttpClient獲取天氣預報 異常及原因


采用httpClient調用天氣預報地址獲取出現異常

2018-10-04 15:18:25.815 ERROR 10868 --- [nio-8080-exec-5] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.web.client.HttpServerErrorException: 502 Bad Gateway] with root cause

org.springframework.web.client.HttpServerErrorException: 502 Bad Gateway
    at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:97) ~[spring-web-5.0.9.RELEASE.jar:5.0.9.RELEASE]
    at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:79) ~[spring-web-5.0.9.RELEASE.jar:5.0.9.RELEASE]
    at org.springframework.web.client.ResponseErrorHandler.handleError(ResponseErrorHandler.java:63) ~[spring-web-5.0.9.RELEASE.jar:5.0.9.RE
LEASE]

當前異常產生原因是調用服務器地址我寫錯了導致的異常

錯誤代碼:

正確的服務地址:

第二個異常json轉換異常

 正確獲取到一個json格式數據后要將當前json字符串轉換成指定類型對象

    private WeatherResponse doGetWeather(String uri){
        //通過spring  restTemplate 客戶端發送請求獲取 String類型響應實體
        ResponseEntity<String> respString = restTemplate.getForEntity(uri, String.class);

        //Springboot內部集成了json操作對象
        ObjectMapper objectMapper = new ObjectMapper();
        WeatherResponse resp=null;
        String strBody = null;
        //通過響應客戶端獲取狀態碼判斷是否為成功狀態碼
        if(respString.getStatusCodeValue()==200){
            //獲取響應實體內容實體
            strBody = respString.getBody();
        }
        try {
            //通過json操作對象將string 類型數據轉為指定類型對象
            resp = objectMapper.readValue(strBody, WeatherResponse.class);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return resp;
    }
}

由於weatherResponse實體內定義的屬性與json 返回屬性不一致

public class WeatherResponse implements Serializable{

    private Weather weather;

    private Integer status;

    private String desc;

json數據屬性:  返回json 數據屬性為data  而實體中屬性Weather 為weather 應該修改為Weather  data   

異常信息:這里會清晰的指出屬性是哪一個問題

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM