java 发送带Basic Auth认证的http post请求实例代码
构造httpheader
privatestaticfinalStringURL="url"; privatestaticfinalStringAPP_KEY="key"; privatestaticfinalStringSECRET_KEY="secret";
/**
*构造BasicAuth认证头信息
*
*@return
*/
privateStringgetHeader(){
Stringauth=APP_KEY+":"+SECRET_KEY;
byte[]encodedAuth=Base64.encodeBase64(auth.getBytes(Charset.forName("US-ASCII")));
StringauthHeader="Basic"+newString(encodedAuth);
returnauthHeader;
}
老方式:
privatevoidsend1(JPushObjectpushObject){
CloseableHttpClientclient=HttpClients.createDefault();
HttpPostpost=newHttpPost(URL);
System.out.println("要发送的数据"+JSON.toJSONString(pushObject));
StringEntitymyEntity=newStringEntity(JSON.toJSONString(pushObject),ContentType.APPLICATION_JSON);//构造请求数据
post.addHeader("Authorization",getHeader());
post.setEntity(myEntity);//设置请求体
StringresponseContent=null;//响应内容
CloseableHttpResponseresponse=null;
try{
response=client.execute(post);
System.out.println(JSON.toJSONString(response));
if(response.getStatusLine().getStatusCode()==200){
HttpEntityentity=response.getEntity();
responseContent=EntityUtils.toString(entity,"UTF-8");
}
System.out.println("responseContent:"+responseContent);
}catch(ClientProtocolExceptione){
e.printStackTrace();
}catch(IOExceptione){
e.printStackTrace();
}finally{
try{
if(response!=null)
response.close();
}catch(IOExceptione){
e.printStackTrace();
}finally{
try{
if(client!=null)
client.close();
}catch(IOExceptione){
e.printStackTrace();
}
}
}
}
httpClient方式
publicvoidsend()throwsClientProtocolException,IOException{
HttpClienthttpClient=HttpClientBuilder.create().build();
HttpPosthttpPost=BaseHttpPost.buildHttpHeader(url);
//设置请求的参数
List<NameValuePair>nvps=newArrayList<NameValuePair>();
nvps.add(newBasicNameValuePair("fromAccid",fromAccid));
nvps.add(newBasicNameValuePair("toAccids",toAccids));
nvps.add(newBasicNameValuePair("type",msgType));
Map<String,Object>body=newHashMap<String,Object>();
body.put("msg",msg);
nvps.add(newBasicNameValuePair("body",JSON.toJSONString(body)));
nvps.add(newBasicNameValuePair("pushcontent",msg));
httpPost.setEntity(newUrlEncodedFormEntity(nvps,"utf-8"));
//执行请求
HttpResponseresponse=httpClient.execute(httpPost);
//打印执行结果
System.out.println(EntityUtils.toString(response.getEntity(),"utf-8"));
}
以上这篇java发送带BasicAuth认证的httppost请求实例代码就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。