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();
}
}
java实现https post请求并携带验证信息
最新推荐文章于 2023-02-22 13:18:10 发布