发送http请求的两种方式(HmacSHA256加密)

本文介绍了如何通过 Commons-HTTPClient 发送POST和GET请求,以及如何利用OkHttp3简化HTTP请求过程。两个库的对比和实践示例有助于理解不同场景下的选择。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


一、使用commons-httpclient发送http请求

  1. 引入pom文件
    <dependency>
      <groupId>commons-httpclient</groupId>
      <artifactId>commons-httpclient</artifactId>
      <version>3.1</version>
    </dependency>
  1. 创建HttpClient对象实例化对象,分别对post和get请求进行处理
public class TestHttpClient {
    public static void main(String[] args) throws IOException {
          String sign = HeaUtil.sha256_HMAC("access_token=U1RzaWQwMDAwMDAxNjQ4MDI0OTk5M23jI4TUtBQmZhdG9uU3Zid3Z3dzlndXBjNUhxenBWdTg1S3F8fDF8djJ8MQ==&openid=120D1802840AAC2CFEEC20DA9BE4E34188Ac00330919c90492f1b28c05c69d9c4c1030", "you-string");
        String url = "https://68b22a800-20883-46251-a9f2-463dde5412244a.bspapp.com/loginPath?access_token=U1RzaWQwMDAwMDAxNjQ42MDI0OTk5MjI4TUtBQmZ2hdG9uU3Zid3Z3dzl2ndXBjNUhxenBWdTg1S3F8fDF8djJ8MQ==&openid=1202D1802840AAC2CFEEC20D2A9BE4E34188Ac003309129c90492fb28c05c69d9c4c1030&sign=" + sign;     	      	  
       System.out.println(sendPost(url ));
       System.out.println(sendGet(url ));

    }

    //通过post请求
    public static String sendPost(String urlParame) throws IOException {
        //创建httpClient实例对象
        HttpClient httpClient=new HttpClient();
        //设置httpClient连接主机服务器超时时间: 以毫秒为单位 1000ms=1s,连接超时:为http连接主机服务器无法在规定时间内完成
        httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(10000);
        //创建post请求方法实例对象
        PostMethod postMethod=new PostMethod(urlParame);
        //设置post请求超时时间,value单位为毫秒    请求超时:请求超时就是连接成功了,但你发出去的请求在指定时间内没有任何回应
        postMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT,10000);
        postMethod.addRequestHeader("Content-Type", "application/json");
        //执行post
        httpClient.executeMethod(postMethod);
        //获得返回
        String result=postMethod.getResponseBodyAsString();
        //释放连接
        postMethod.releaseConnection();
        return result;
    }

    public static String sendGet(String urlParame) throws IOException {
        //创建httpclient实例
        HttpClient httpClient=new HttpClient();
        //设置httpclient连接主机服务器超时时间: 以毫秒为单位 1000ms=1s
        httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(10000);
        //创建get请求方法实例对象
        GetMethod getMethod=new GetMethod(urlParame);
        //设置get请求超时时间,value以毫秒为单位
        getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT,10000);
        //设置请求头
        getMethod.addRequestHeader("Content-Type", "application/json");
        //执行get
        httpClient.executeMethod(getMethod);
        //获取返回数据
        String result=getMethod.getResponseBodyAsString();
        //释放http连接
        getMethod.releaseConnection();

        return result;
    }
}

public class HeaUtil {
    /**
     * sha256_HMAC加密
     *
     * @param message 消息
     * @param secret  秘钥
     * @return 加密后字符串
     */
    public static String sha256_HMAC(String message, String secret) {
        String hash = "";
        try {
            Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
            SecretKeySpec secret_key = new SecretKeySpec(secret.getBytes(), "HmacSHA256");
            sha256_HMAC.init(secret_key);
            byte[] bytes = sha256_HMAC.doFinal(message.getBytes());
            hash = byteArrayToHexString(bytes);
        } catch (Exception e) {
            System.out.println("Error HmacSHA256 ===========" + e.getMessage());
        }
        return hash;
    }

    /**
     * 将加密后的字节数组转换成字符串
     *
     * @param b 字节数组
     * @return 字符串
     */
    private static String byteArrayToHexString(byte[] b) {
        StringBuilder hs = new StringBuilder();
        String stmp;
        for (int n = 0; b != null && n < b.length; n++) {
            stmp = Integer.toHexString(b[n] & 0XFF);
            if (stmp.length() == 1)
                hs.append('0');
            hs.append(stmp);
        }
        return hs.toString().toLowerCase();
    }
}

二、使用okhttp3发送http请求

  1. 引入pom文件
    <dependency>
            <groupId>com.squareup.okhttp3</groupId>
            <artifactId>okhttp</artifactId>
            <version>4.5.0</version>
        </dependency>
  1. 对get请求进行处理
 public static void main(String[] args) {
         OkHttpClient okHttpClient = new OkHttpClient();
            Request.Builder builder = new Request.Builder();
            Request build = builder.get().url("你的url").build();
            Call call = okHttpClient.newCall(build);
            call.execute();
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值