通过httpClient访问第三方API

一个访问知心天气的demo,知心天气官方API详情可见:http://www.thinkpage.cn/doc#now
这里只做其中的逐日天气预报和昨日天气 ,此接口属于其中的免费接口,可以获取指定地区,指定时间段内的天气信息。

创建项目,引入依赖

<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.4.1.RELEASE</version>
    </parent>


    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
        </dependency>

        <!-- web支持 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!-- Springboot 热部署 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional>
        </dependency>
        <!-- httpClient -->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.3.6</version>
        </dependency>
        <!-- fastJson -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.4</version>
        </dependency>
    </dependencies>

创建请求实体ZhiXinRequest

private String method;
    private String location;
    private String language;
    private String start;
    private String days;
    private String unit;

    //省略set,get...

创建响应实体ZhiXinResponse

public class ZhiXinResponse {
    private List<Results> results;
    private String status;
    private String status_code;
    //省略set,get...
}
public class Results {
    private Location location;
    private List<Daily> daily;
    private String last_update;

    //省略set,get...

    class Daily {
        private String date;
        private String text_day;
        private String code_day;
        private String text_night;
        private String code_night;
        private String high;
        private String low;
        private String precip;
        private String wind_scale;

        //省略set,get...
    }

    class Location {
        private String id;
        private String name;
        private String country;
        private String path;
        private String timezone;
        private String timezone_offset;

        //省略set,get...
    }
}

创建ZhiXinAPI,具体的接口参数规则见:http://www.thinkpage.cn/doc#now

public class ZhiXinAPI {
    // 要访问的地址
    private String url = "https://api.thinkpage.cn/v3";
    // API密钥(虽然是免费的接口,但是暴露出来不知道会不会有问题~~)
    private String authKey = "?key=9qwasjjhtafmbxz7";
    // 创建默认的httpClient实例
    private CloseableHttpClient client = HttpClients.custom().build();

    /**
     * 发送请求,接收返回信息。
     * 只作为demo,忽略异常,未关闭连接
     */
    public ZhiXinResponse sendRequest(ZhiXinRequest zhiXinRequest) throws ParseException, IOException {
        // 组装对象
        url = url + zhiXinRequest.getMethod() + authKey;
        if (zhiXinRequest.getLocation() != null) {
            url = url + "&location=" + zhiXinRequest.getLocation();
        }
        if (zhiXinRequest.getStart() != null) {
            url = url + "&start=" + zhiXinRequest.getStart();
        }
        if (zhiXinRequest.getDays() != null) {
            url = url + "&days=" + zhiXinRequest.getDays();
        }
        // 创建http请求(get方式)  
        HttpGet httpGet = new HttpGet(url);
        httpGet.setHeader("Content-Type", "application/json-rpc");
        System.out.println("httpGet: " + httpGet);
        // 发送请求并接收结果(这里已经接收了到了返回结果,后面的代码只做了一些转换)
        HttpResponse httpResponse = client.execute(httpGet);
        String responseBody = EntityUtils.toString(httpResponse.getEntity());
        ZhiXinResponse zhiXinResponse = JSON.parseObject(responseBody, ZhiXinResponse.class);
        System.out.println("response: " + responseBody);
        return zhiXinResponse;
    }
}

创建springboot启动类Application

@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

创建服务控制类ZhiXinController

@Controller
@RestController
public class ZhiXinController {

    @RequestMapping("daily")
    public String getWeatherDaily(String location, String days) throws ParseException, IOException {

        ZhiXinRequest zhiXinRequest = new ZhiXinRequest();
        // 要查询的城市
        zhiXinRequest.setLocation(location);
        // 要查询的天数
        zhiXinRequest.setDays(days);
        // 要访问的接口
        String method = "/weather/daily.json";
        zhiXinRequest.setMethod(method);
        ZhiXinAPI zhiXinAPI = new ZhiXinAPI();
        // 发送并接收返回的信息
        ZhiXinResponse zhiXinResponse = zhiXinAPI.sendRequest(zhiXinRequest);
        // 将信息转换成json
        String result = JSON.toJSONString(zhiXinResponse);
        return result;
    }
}

启动服务,通过访问http://localhost:8080/daily?location=beijing&days=1 即可得到指定的天气信息。

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值