HttpClients调用外部api

自闭症网瘾萝莉.ら 提交于 2020-02-08 14:34:24
package com.example.demo;

import com.alibaba.fastjson.JSONObject;
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.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;



@RestController
public class HttpClientsController {
    @RequestMapping
    public JSONObject HttpClientsTest() {
        JSONObject jo = null;
        try {
            String url = "http://api.csslcloud.net/api/v2/record/info";
            CloseableHttpClient httpClient = HttpClients.createDefault();
            HttpGet httpGet = new HttpGet(url);
            httpGet.setHeader("Connection", "keep-alive");
            httpGet.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36");
            CloseableHttpResponse httpResponse = httpClient.execute(httpGet);
            String string = EntityUtils.toString(httpResponse.getEntity());
            jo = JSONObject.parseObject(string);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return jo;
    }
}

在这里插入图片描述

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!