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

引入HttpClient依赖


    org.apache.httpcomponents
    httpclient
4.5

目录结构如下

SprintBoot菜鸟入门(三)---使用HttpClient发送Get请求json格式数据_第1张图片

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

在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 getInfo(){
        Map result = new HashMap();
        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

SprintBoot菜鸟入门(三)---使用HttpClient发送Get请求json格式数据_第2张图片

 结束

你可能感兴趣的:(java,springboot,java,spring,boot)