JAVA Http的Post请求传参、添加Authorization Basic Auth总结

本文介绍如何使用PostMan工具设置HTTP Basic Auth认证,并通过JAVA代码发送带有验证信息的POST请求。

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

PostMan添加Authorization验证

JAVA代码实现 

String url ="URL路径";
Map<String, String> prarms = new HashMap<>();
prarms.put("userName","案例");
prarms.put("age", "18");
String jsonPrarms = JSON.toJSONString(prarms);
CloseableHttpClient httpClient = HttpClientBuilder.create().build();   //获取浏览器信息
HttpPost httpPost = new HttpPost(url);
String encoding = DatatypeConverter.printBase64Binary("username:password".getBytes("UTF-8"));  //username  password 自行修改  中间":"不可少
httpPost.setHeader("Authorization", "Basic " + encoding);
HttpEntity entityParam = new StringEntity(jsonPrarms,ContentType.create("application/json", "UTF-8"));  //这里的“application/json” 可以更换因为本人是传的json参数所以用的这个
httpPost.setEntity(entityParam);     //把参数添加到post请求
HttpResponse response = httpClient.execute(httpPost);
StatusLine statusLine = response.getStatusLine();   //获取请求对象中的响应行对象
int responseCode = statusLine.getStatusCode();
if (responseCode == 200) {
    //获取响应信息
    HttpEntity entity = response.getEntity();
    InputStream input = entity.getContent();
    BufferedReader br = new BufferedReader(new InputStreamReader(input,"utf-8"));
    String str1 = br.readLine();
    System.out.println("服务器的响应是:" + str1);
    br.close();
    input.close();
} else {
    System.out.println("响应失败");
}

不足之处欢迎指出。

评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值