basic auth java_java 发送带Basic Auth认证的http post请求实例代码

构造http header

private static final String URL = "url";

private static final String APP_KEY = "key";

private static final String SECRET_KEY = "secret";

/**

* 构造Basic Auth认证头信息

*

* @return

*/

private String getHeader() {

String auth = APP_KEY + ":" + SECRET_KEY;

byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(Charset.forName("US-ASCII")));

String authHeader = "Basic " + new String(encodedAuth);

return authHeader;

}

老方式:

private void send1(JPushObject pushObject) {

CloseableHttpClient client = HttpClients.createDefault();

HttpPost post = new HttpPost(URL);

System.out.println("要发送的数据" + JSON.toJSONString(pushObject));

StringEntity myEntity = new StringEntity(JSON.toJSONString(pushObject), ContentType.APPLICATION_JSON);// 构造请求数据

post.addHeader("Authorization", getHeader());

post.setEntity(myEntity);// 设置请求体

String responseContent = null; // 响应内容

CloseableHttpResponse response = null;

try {

response = client.execute(post);

System.out.println(JSON.toJSONString(response));

if (response.getStatusLine().getStatusCode() == 200) {

HttpEntity entity = response.getEntity();

responseContent = EntityUtils.toString(entity, "UTF-8");

}

System.out.println("responseContent:" + responseContent);

} catch (ClientProtocolException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

} finally {

try {

if (response != null)

response.close();

} catch (IOException e) {

e.printStackTrace();

} finally {

try {

if (client != null)

client.close();

} catch (IOException e) {

e.printStackTrace();

}

}

}

}

httpClient方式

public void send() throws ClientProtocolException, IOException {

HttpClient httpClient = HttpClientBuilder.create().build();

HttpPost httpPost = BaseHttpPost.buildHttpHeader(url);

// 设置请求的参数

List nvps = new ArrayList();

nvps.add(new BasicNameValuePair("fromAccid", fromAccid));

nvps.add(new BasicNameValuePair("toAccids", toAccids));

nvps.add(new BasicNameValuePair("type", msgType));

Map body = new HashMap();

body.put("msg", msg);

nvps.add(new BasicNameValuePair("body", JSON.toJSONString(body)));

nvps.add(new BasicNameValuePair("pushcontent", msg));

httpPost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));

// 执行请求

HttpResponse response = httpClient.execute(httpPost);

// 打印执行结果

System.out.println(EntityUtils.toString(response.getEntity(), "utf-8"));

}

以上这篇java 发送带Basic Auth认证的http post请求实例代码就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值