解决中国天气网天气预报API返回数据乱码问题

      最近项目中选择从中国天气网取天气预报数据,api地址是:http://www.weather.com.cn/data/cityinfo/101110101.html。其中101110101是城市的代码,具体需要哪个城市,城市代码可以在百度搜。

期初取到的数据中文和符号都是乱码,最后通过以下方法解决。首先定义获取方法:

            String url = "http://www.weather.com.cn/data/cityinfo/101110101.html";
            String weatherInfo = WeatherUtil.getWeatherInfo(url);
WeatherUtil为获取具体气象数据的工具类:
 public static String getWeatherInfo(String url) {
        CloseableHttpClient client;
        client = HttpClients.createDefault();

        HttpGet get = new HttpGet(url);
        HttpResponse response;
        try {
            response = client.execute(get);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                InputStream instreams = entity.getContent();
                String str = WeatherUtil.convertStreamToString(instreams);
                get.abort();
                return str;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    private static String convertStreamToString(InputStream is) {
        StringBuilder sb1 = new StringBuilder();
        byte[] bytes = new byte[4096];
        int size;

        try {
            while ((size = is.read(bytes)) > 0) {
                String str = new String(bytes, 0, size, "UTF-8");
                sb1.append(str);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb1.toString();
    }
这样就可以解决返回乱码的问题

你可能感兴趣的:(java)