SprintBoot菜鸟入门(三)---使用HttpClient发送Get请求json格式数据

引入HttpClient依赖

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

目录结构如下

目的如下:写一个接口,接口返回的数据是请求另一个接口的

在APIController中新加一个方法

package com.yunprophet.yunprophet.Controller;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.net.URL;
import java.net.Proxy;


@RestController
@RequestMapping("/api")
public class APIController {

    @RequestMapping("/getinfo")
    public Map<String , Object> getInfo(){
        Map<String , Object> result = new HashMap<String , Object>();
        result.put("code","200");
        result.put("msg","成功");
        return result;
    }

    @RequestMapping("/getarticlelist")
    public String getArticleList() throws IOException {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet("https://www.guanacossj.com/blog/showarticles/");
        CloseableHttpResponse response = null;
        String result = "";
        try {
            // 执行请求,相当于敲完地址后按下回车。获取响应
            response = httpclient.execute(httpGet);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                // 解析响应,获取数据
                String content = EntityUtils.toString(response.getEntity(), "UTF-8");
                System.out.println(content);
                result = content;
            }
        } finally {
            if (response != null) {
                // 关闭资源
                response.close();
            }
            // 关闭浏览器
            httpclient.close();
        }
        return result;
    }
}

使用postman测试一下,发送get请求http://127.0.0.1:8080/api/getarticlelist

 结束

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值