springboot 使用第三方接口api实现天气预报功能

1、查询天气的api:“http://aider.meizu.com/app/weather/listWeather?cityIds=101210101”
2、直接在city=后面加上中文城市,就会返回json数据。
3、基于maven创建一个springboot应用,pom信息如下,注意添加了httpclien

依赖

 <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
        </dependency>

 配置类

package com.ruoyi.user.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;

@Configuration
public class WeatherConfig {
    @Bean
    public RestTemplate restTemplate(){
        RestTemplate restTemplate = new RestTemplate(new HttpComponentsClientHttpRequestFactory());
        restTemplate.getMessageConverters().set(1,new StringHttpMessageConverter(StandardCharsets.UTF_8));
        return  restTemplate;
    }

}

  测试

@Test
    public void test30(@Autowired
                           RestTemplate restTemplate) throws IOException {
        String apiURL ="http://wthrcdn.etouch.cn/weather_mini?city=广州";
        ResponseEntity<String> forEntity = restTemplate.getForEntity(apiURL, String.class);

        if (200 == forEntity.getStatusCodeValue()){
            System.out.println(forEntity.getBody());
        }else {
            System.out.println(("error with code:" + forEntity.getStatusCodeValue()));
        }
    }

  

posted @ 2022-08-30 19:09  古家杰  阅读(509)  评论(0)    收藏  举报