HttpClients call external api

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;
    }
}

Here Insert Picture Description

Published 17 original articles · won praise 1 · views 651

Guess you like

Origin blog.csdn.net/qq_23355059/article/details/104219732