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

网友投稿 621 2023-06-30


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

构造http header

private static final String URL = "url";

private static fhttp://inal 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() == 200kKHgis) {

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 Bahttp://sicNameValuePair("pushcontent", msg));

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

// 执行请求

HttpResponse response = httpClient.execute(httpPost);

// 打印执行结果

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

}


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:java发送HttpClient请求及接收请求结果过程的简单实例
下一篇:Java中嵌入式MySQL的使用方法
相关文章

 发表评论

暂时没有评论,来抢沙发吧~