https调用接口,设置header,Get请求传body参数

参考文章:

https://icode.best/i/76678935328881

【java】实现Get请求传body参数_java 实现get请求body传参-CSDN博客

看到get请求,参数还在请求体body里,感觉很多人都是骂骂咧咧的,这简直就是个奇葩人才能写这样的接口方式吧,但没办法,人家给的接口文档就这样,只能硬着头皮调喽。

public static void getDatas(){
        String url = "https://ip地址:端口号/test/v1.0";
        Map<String, Object> map = new HashMap<>();
        map.put("fromIndex", 1);
        map.put("toIndex", 10);
        map.put("fromTime", "20240102153045");
        map.put("toTime", "20240723153045");
        String reqParams = JSONArray.toJSONString(map);
        try {

            //调用登录接口
            HttpResponse loginRes = getAccessToken();
            String SetCookie = loginRes.getHeaders().get("Set-Cookie");
            log.info("Set-Cookie: " + SetCookie);
            String[] Cookie = SetCookie.split(";");
            String cookie = Cookie[0];
            log.info("Cookie: " + cookie);

            String datas = sendJsonByGetReq(url, reqParams, "UTF-8",cookie);
            log.info("请求Get请求返回结果:"+datas);


            //解析
            JSONObject jsonObject = JSON.parseObject(datas);
            JSONArray alarmEventList = jsonObject.getJSONArray("alarmEventList");

            // 遍历alarmEventList并打印每个元素
            for (int i = 0; i < alarmEventList.size(); i++) {
                JSONObject alarmEvent = alarmEventList.getJSONObject(i);
                JSONObject alarmNotify =  alarmEvent.getJSONObject("alarmNotify");
                JSONObject operateInfo =  alarmEvent.getJSONObject("operateInfo");
                System.out.println("alarmEvent:"  + alarmEvent);
                System.out.println("alarmNotify:"  + alarmNotify);

   
            }


        } catch (Exception e) {
            e.printStackTrace();
        }
    }
package com.xxx.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.*;
import java.nio.charset.Charset;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import org.apache.http.client.methods.HttpGet;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.ssl.TrustStrategy;
import org.apache.http.conn.ssl.NoopHostnameVerifier;

import javax.net.ssl.SSLContext;
import java.io.IOException;

@Slf4j
public class httpUtil {
    
    
    /**
     * 获取服务器信任
     */
    private static void getTrust(){
        try {
            HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String s, SSLSession sslSession) {
                    return true;
                }
            });
            SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null,new X509TrustManager[]{ new X509TrustManager() {
                @Override
                public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {

                }
                @Override
                public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {

                }
                @Override
                public X509Certificate[] getAcceptedIssuers() {
                    return new X509Certificate[0];
                }
            }},new SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    TrustManager[] trustAllCerts = new TrustManager[] {
            new X509TrustManager() {
                public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) { }
                public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) { }
                public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; }
            }
    };


    private static final TrustStrategy trustStrategy = (cert, authType) -> true;
    private static final SSLContext sslContext;

    static {
        try {
            sslContext = SSLContexts.custom()
                    .loadTrustMaterial(null, trustStrategy)
                    .build();
        } catch (Exception e) {
            throw new RuntimeException("Failed to initialize the SSL context", e);
        }
    }

    

    public static String sendJsonByGetReq(String url, String param, String encoding, String cookie) throws IOException {
        // 创建 httpclient 对象
        try (CloseableHttpClient client = HttpClients.custom()
                .setSSLContext(sslContext)
                .setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
                .build()) {

            log.info("http get请求开始: " + cookie);
            String body = "";
            //创建httpclient对象
            HttpGetWithEntity httpGetWithEntity = new HttpGetWithEntity(url);
            HttpEntity httpEntity = new StringEntity(param, ContentType.APPLICATION_JSON);
            httpGetWithEntity.setEntity(httpEntity);
            httpGetWithEntity.setHeader("Content-Type", "application/json;charset=UTF-8");
            httpGetWithEntity.setHeader("Cookie", cookie);
            //执行请求操作,并拿到结果(同步阻塞)
            CloseableHttpResponse response = client.execute(httpGetWithEntity);
            //获取结果实体
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                //按指定编码转换结果实体为String类型
                body = EntityUtils.toString(entity, encoding);
            }
            //释放链接
            response.close();
            return body;

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.xxx.jsservercommom.util.ResultBack;
import com.xxx.jsservercommom.util.ResultStatus;
import com.xxx.yyy.util.entity.Http;
import com.xxx.yyy.util.entity.HttpResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.client.RestTemplate;
import javax.annotation.Resource;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import static com.xxx.util.HttpsUtil.httpsRequest;
import static com.xxx.util.httpUtil.sendJsonByGetReq;


/**
 * 登录调用接口工具类
 */
@Component
@Slf4j
public class AdminUtil {


    public static HttpResponse getAccessToken() {
        log.info("调用登录接口开始: ");
        // 创建一个 Map 来存放请求头
        Map<String, String> headerMap = new HashMap<>();
        headerMap.put("Content-Type", "application/json;charset=UTF-8");

        // 创建一个 Http 对象(这里只是示例,实际中你需要根据你的 Http 类来创建)
        // 假设 Http 类有 setType, setIp, setPort, setUrl, setParam 方法
        Http http = new Http();
        http.setType("https"); // 假设这是设置请求类型的方法,这里使用枚举值的字符串表示
        http.setIp("ip");
        http.setPort("端口");
        http.setUrl("/loginInfo/login/v1.0");

        // 假设 setParam 方法接受一个 Map,这里简单用 Map 示例
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("userName", "abc");
        paramMap.put("password", "def");
        http.setParam(paramMap); // 假设 Http 类有合适的方法来接收参数
        http.setMethod("post");

        try {
            // 调用 httpsRequest 方法
            HttpResponse response = httpsRequest(headerMap, http);
            // 处理响应
            log.info("Response Status Code: " + response.getStatus());
            log.info("Response Body: " + response.getBody());
            // 输出响应头
            for (Map.Entry<String, String> entry : response.getHeaders().entrySet()) {
                log.info("Header: " + entry.getKey() + " = " + entry.getValue());
            }
            return response;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

   
}
package com.dfzh.shanm.jsservervideo.util;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.xxx.util.entity.Http;
import com.xxx.util.entity.HttpResponse;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;

import javax.net.ssl.*;
import java.io.IOException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @ClassName: HttpsUtil
 * @Description: rest接口访问工具类(暂时只有HTTPS模式的GET,后续有需要添加)
 * @Version 1.0
 */
@Slf4j
public class HttpsUtil {

    /**
     * 请求超时时间
     */
    public static final int TIME_OUT = 200000;

    /**
     * https-优化后
     * 枚举值:type
     * 1:Post
     * 2:Get
     * 3:Put
     */
    public static HttpResponse httpsRequest(Map<String, String> headerMap, Http http) throws IOException {

        String requestUrl = http.getType() + "://"
                + http.getIp() + ":"
                + http.getPort()
                + http.getUrl();
        if (null == requestUrl || requestUrl.isEmpty()) {
            throw new RuntimeException("The request URL is blank.");
        }
        log.info("请求url: "+requestUrl+"请求入参 :"+http.getParam() +"请求头:" +headerMap);
        //如果是https请求
        if (requestUrl.startsWith("https")) {
            getTrust();
        }

        Connection connect = Jsoup.connect(requestUrl);

        connect.timeout(TIME_OUT);
        connect.ignoreContentType(true);
        connect.maxBodySize(0);
        if (headerMap != null) {
            connect.headers(headerMap);
            log.info("请求头:{}", connect.toString());
        }
        if (http.getMethod().equals("get")) {
            connect.method(Connection.Method.GET);
            if (http.getParam() != null) {
                connect.data(JSON.toJSONString(http.getParam()));
            }
        } else if (http.getMethod().equals("post")) {
            connect.method(Connection.Method.POST);
            connect.requestBody(JSON.toJSONString(http.getParam()));
        } else if (http.getMethod().equals("put")) {
            connect.method(Connection.Method.PUT);
            connect.requestBody(JSON.toJSONString(http.getParam()));
        }
        Connection.Response execute = connect.execute();
        log.info(http.getMethod() + "方法请求出参状态码"+execute.statusCode());
        log.info(http.getMethod() + "方法请求出参"+execute.body());
        // 提取响应头
        Map<String, String> responseHeaders = new HashMap<>();
        for (Map.Entry<String, String> header : execute.headers().entrySet()) {
            responseHeaders.put(header.getKey(), header.getValue());
        }
        HttpResponse httpResponse = new HttpResponse(execute.statusCode(),execute.body(),responseHeaders);
        return httpResponse;
    }

    /**
     * 获取服务器信任
     */
    private static void getTrust(){
        try {
            HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String s, SSLSession sslSession) {
                    return true;
                }
            });
            SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null,new X509TrustManager[]{ new X509TrustManager() {
                @Override
                public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {

                }
                @Override
                public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {

                }
                @Override
                public X509Certificate[] getAcceptedIssuers() {
                    return new X509Certificate[0];
                }
            }},new SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
package com.xxx.util.entity;

import java.util.Map;

/**
 * @ClassName: HttpResponse
 * @Description: TODO
 * @Version 1.0
 */
public class HttpResponse {

    int status;
    String body;
    private Map<String, String> headers;

    public HttpResponse(int status, String body, Map<String, String> headers) {
        this.status=status;
        this.body=body;
        this.headers = headers;
    }

    public int getStatus() {
        return status;
    }

    public String getBody() {
        return body;
    }

    public Map<String, String> getHeaders() {
        return headers;
    }

}
package com.xxx.util.entity;

import lombok.Data;

/**
 * @ClassName: 请求信息
 * @Description: TODO
 * @Version 1.0
 */
@Data
public class Http {

    //接口后缀
    String url;
    String ip;
    String port;
    //接口入参
    Object param;
    //接口访问方式(https,http)
    String type;
    //接口方法
    String method;

}

总结,一个是登录时用到的HttpsUtil中的httpsRequest方法,常规调用。

一个就是奇葩的get调用参数写在请求体里httpUtil中的sendJsonByGetReq

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值