httpget请求与获取返回值

发布于:2025-06-30 ⋅ 阅读:(13) ⋅ 点赞:(0)

首先需要在pom中添加对应包信息

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.13</version>
</dependency>
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>2.0.23</version>
</dependency>
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpcore</artifactId>
    <version>4.4.15</version>
</dependency>
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-api</artifactId>
    <version>2.0.7</version>
</dependency>
package com.inspur.ides.resourceinventory.server.controller;

import com.alibaba.fastjson2.*;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.util.ArrayList;
import java.util.List;

public class testDemo {

    public static void main(String[] args) {
        HttpClient httpClient = HttpClients.createDefault();
        // 获取列表
        HttpGet httpGet = new HttpGet("http://ip:8080/resource/list");
        // 身份校验
        httpGet.addHeader("Cookie", "iqevalToken=ea68b453-bdfc-416e-8eb0-c80593defa5a;");

        try {
            HttpResponse response = httpClient.execute(httpGet);
            HttpEntity entity = response.getEntity();

            if (entity != null) {
                String result = EntityUtils.toString(entity);
                // 组装结果
                JSONObject pa = JSONObject.parseObject(result);
                if ("操作成功".equals(pa.get("resultDesc"))) {
                    JSONObject pa1 = JSONObject.parseObject(pa.get("data").toString());
                    List<Long> ids = new ArrayList<>();
                    JSONArray data = JSON.parseArray(pa1.get("data").toString());
                    for (int i = 0; i < data.size(); i ++) {
                        JSONObject pa2 = JSONObject.parseObject(data.get(i).toString());
                        // 删除数据
                        httpGet = new HttpGet("http://ip:8080/resource/delete?id=" + pa2.get("id").toString());
                        httpGet.addHeader("Cookie", "iqevalToken=ea68b453-bdfc-416e-8eb0-c80593defa5a;");
                        response = httpClient.execute(httpGet);
                        entity = response.getEntity();
                        result = EntityUtils.toString(entity);
                        // 输出删除结果
                        System.out.println(result);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}


网站公告

今日签到

点亮在社区的每一天
去签到