博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
综合数据api接口使用
阅读量:6980 次
发布时间:2019-06-27

本文共 7377 字,大约阅读时间需要 24 分钟。

由于请求数据接口是跨域的,但是我们无法改变接口的代码

先从请求后台,然后从后台进行二次请求,请求数据接口

原生代码

package edu.nf.http.test;import org.apache.http.HttpEntity;import org.apache.http.client.methods.CloseableHttpResponse;import org.apache.http.client.methods.HttpUriRequest;import org.apache.http.client.methods.RequestBuilder;import org.apache.http.impl.client.CloseableHttpClient;import org.apache.http.impl.client.HttpClients;import org.apache.http.util.EntityUtils;import org.junit.Test;import java.io.IOException;/** * @Author Eric * @Date 2018/12/10 */public class HttpClientTest {    @Test    public void testGet(){        //创建一个HttpClient对象,用于发送请求和接收响应信息        CloseableHttpClient client = HttpClients.createDefault();        //创建请求构建起(工厂)        RequestBuilder builder = RequestBuilder.get();        //设置请求的uri        builder.setUri("http://c.3g.163.com/nc/article/list/T1348647853363/0-40.html");        //创建一个get请求对象        HttpUriRequest request = builder.build();        //发送请求,并返回响应对象        try {            CloseableHttpResponse response = client.execute(request);            //从响应对象中获取数据,这里使用了一个HttpEntity封装            HttpEntity entity = response.getEntity();            //从Entity中获取真正的响应内容            String json = EntityUtils.toString(entity);            System.out.println(json);        } catch (IOException e) {            e.printStackTrace();            throw new RuntimeException(e.getMessage());        }    }    @Test    public void testPost(){        //创建一个HttpClient对象,用于发送请求和接收响应信息        CloseableHttpClient client = HttpClients.createDefault();        RequestBuilder builder = RequestBuilder.post();        builder.setUri("http://c.3g.163.com/nc/article/list/T1348647853363/0-40.html");        //可以提交参数        builder.addParameter("user","admin").addParameter("age","18");        //构建请求对象        HttpUriRequest request = builder.build();        //发送请求        try {            CloseableHttpResponse response = client.execute(request);            //获取响应数据            HttpEntity entity = response.getEntity();            String json = EntityUtils.toString(entity);            System.out.println(json);        } catch (IOException e) {            e.printStackTrace();            throw new RuntimeException(e.getMessage());        }    }}

封装成工具类

package edu.nf.http.conmmons;import org.apache.http.HttpEntity;import org.apache.http.client.methods.CloseableHttpResponse;import org.apache.http.client.methods.HttpUriRequest;import org.apache.http.client.methods.RequestBuilder;import org.apache.http.impl.client.CloseableHttpClient;import org.apache.http.impl.client.HttpClients;import org.apache.http.util.EntityUtils;import java.io.IOException;import java.util.Map;/** * @Author Eric * @Date 2018/12/10 * 封装工具类 */public class HttpUtils {    /**     * 创建一个唯一的client对象     */    private static CloseableHttpClient client = HttpClients.createDefault();    /**     * 发送get请求     * @param uri     * @return     */    public static String get(String uri){        //构建get请求        HttpUriRequest request = RequestBuilder.get(uri).build();        return execute(request);    }    /**     * 发送post请求     * @param uri     * @param params post所提交的参数     * @return     */    public static String post(String uri, Map
params){ RequestBuilder builder = RequestBuilder.post(uri); //循环设置参数 for (String name : params.keySet()) { builder.addParameter(name,params.get(name)); } HttpUriRequest request = builder.build(); return execute(request); } /** * 发送请求并返回响应内容 * @param request * @return */ private static String execute(HttpUriRequest request){ try { //发送请求 CloseableHttpResponse response = client.execute(request); HttpEntity entity = response.getEntity(); return EntityUtils.toString(entity); } catch (IOException e) { e.printStackTrace(); throw new RuntimeException(e.getMessage()); } }}

json序列化工具类

(获取到的数据是字符串,序列化成json)

package edu.nf.http.conmmons;import com.fasterxml.jackson.databind.ObjectMapper;import java.io.IOException;/** * @Author Eric * @Date 2018/12/10 */public class JsonUtils {    public static
T convert(String json,Class
clazz){ ObjectMapper mapper = new ObjectMapper(); try { return mapper.readValue(json,clazz); } catch (IOException e) { e.printStackTrace(); throw new RuntimeException(e.getMessage()); } }}

Service过滤

package edu.nf.http.service;import edu.nf.http.conmmons.HttpUtils;import edu.nf.http.conmmons.JsonUtils;import org.springframework.stereotype.Service;import java.util.List;import java.util.Map;/** * @Author Eric * @Date 2018/12/10 */@Servicepublic class NewsService {    public List
> listNews(){ String json = HttpUtils.get("http://c.3g.163.com/nc/article/list/T1348647853363/0-40.html"); //将json转换成Map对象 Map
>> map = JsonUtils.convert(json,Map.class); //进行数据清洗(过滤) List
>list = map.get("T1348647853363"); //删除头行没用的数据 list.remove(0); return list; } public static void main(String[] args) { List
>list = new NewsService().listNews(); System.out.println(list.size()); }}

ResponseVO

package edu.nf.http.controller.vo;/** * @Author Eric * @Date 2018/12/6 */public class ResponseVO
{ private Integer code; private String message; private T data; @Override public String toString() { return "ResponseVO{" + "code=" + code + ", message='" + message + '\'' + ", data=" + data + '}'; } public Integer getCode() { return code; } public void setCode(Integer code) { this.code = code; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public T getData() { return data; } public void setData(T data) { this.data = data; }}

Controller

package edu.nf.http.controller;import edu.nf.http.controller.vo.ResponseVO;import edu.nf.http.service.NewsService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.http.HttpStatus;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RestController;import java.util.List;import java.util.Map;/** * @Author Eric * @Date 2018/12/10 */@RestControllerpublic class NewsController {    @Autowired    private NewsService newsService;    @GetMapping("/listNews")    public ResponseVO listNews(){        ResponseVO vo = new ResponseVO();        List
> list = newsService.listNews(); vo.setCode(HttpStatus.OK.value()); vo.setMessage("无数据"); vo.setData(list); return vo; }}

HTML

(使用Postman工具进行请求可以查看返回的字段,在页面可以用对象进行输出)

            
新闻头条

今日头条

简单列表
  • 标题
    子标题

 

转载于:https://www.cnblogs.com/ssjf/p/10104820.html

你可能感兴趣的文章
解压即用,Ubuntu上Nginx/Apache/PHP编译打包
查看>>
详解-斗鱼弹幕API-接入(斗鱼弹幕服务器第三方接入协议)
查看>>
table设置border没有空隙
查看>>
升级 Vim 7.4 On Ubuntu 13.10, 13.04, 12.04, Linux...
查看>>
Maven的setting.xml 配置详解
查看>>
Pycharm中autopep8设置
查看>>
Python3.7源码在windows(VS2015)下的编译和安装
查看>>
在Java中如何避免“!=null”式的判空语句?
查看>>
手动编译内核
查看>>
openshift client 命令 之 groups
查看>>
vsphere web client 加载不上本地镜像提示加载插件超时
查看>>
db2 之 入门实验
查看>>
开始Jquery的学习生涯
查看>>
手机测试项目时报INSTALL_FAILED_INSUFFICIENT_STORAGE
查看>>
10_css选择符类型1.html
查看>>
修改 liteide 的 godoc 文档样式
查看>>
阿里镜像
查看>>
python 实现脚本上传远程服务并执行脚本
查看>>
Direct2D (39) : 使用 IDWriteTextLayout.Draw() 方法绘制文本
查看>>
突然想起曾经一面试官问我 | 和 || 的区别
查看>>