java实现https post请求并携带验证信息

public static Response getGPS() {

    //发送请求的URL
    String url = "https://api.r-guardian.com/product/batch/info";
    //编码格式
    try {
        String charset = "UTF-8";

        //请求内容

        ArrayList<String> list = new ArrayList<>();
        list.add("xxx");
        
        macAddress macAddress = new macAddress();
        macAddress.setMacAddress(list);
        String s = JSON.toJSONString(macAddress);


        //使用帮助类HttpClients创建CloseableHttpClient对象.

        CloseableHttpClient client = HttpClients.createDefault();

       //HTTP请求类型创建HttpPost实例

        HttpPost post = new HttpPost(url);

       //使用addHeader方法添加请求头部,诸如User-Agent, Accept-Encoding等参数.

        post.setHeader("Content-Type", "application/json;charset=UTF-8");
        //填写账号密码
        post.addHeader("Authorization", "Basic " + Base64.getUrlEncoder().encodeToString(("username" + ":" + "password").getBytes()));


         //组织数据
        StringEntity se = new StringEntity(s);
        //设置编码格式

        se.setContentEncoding(charset);

        //设置数据类型

        se.setContentType("application/json");

        //对于POST请求,把请求体填充进HttpPost实体.

        post.setEntity(se);

        //通过执行HttpPost请求获取CloseableHttpResponse实例 ,从此CloseableHttpResponse实例中获取状态码,错误信息,以及响应页面等等.

        CloseableHttpResponse response = client.execute(post);

        //通过HttpResponse接口的getEntity方法返回响应信息,并进行相应的处理 

        HttpEntity entity = response.getEntity();

        String resData = EntityUtils.toString(response.getEntity());
        Response response1 = JSON.parseObject(resData, Response.class);

        //最后关闭HttpClient资源.
        client.close();
        return response1;
    } catch (Exception e) {
        throw new RuntimeException();
    }

}
  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值