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 send(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() == ) {
HttpEntity entity = response.getEntity();
responseContent = EntityUtils.toString(entity, "UTF-8");
}
if (response != null)
response.close();
if (client != null)
client.close();
System.out.println("responseContent:" + responseContent);
} catch(ClientProtocolException e) {
e.printStackTrace();
} catch(IOException e) {
e.printStackTrace();
}
}
方式二:
引用到的jar: httpclient-4.5.jar; httpcore-4.4.1.jar; commons-logging-1.2.jar; common-codec-1.9.jar
import java.io.IOException; import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils; public class HttpClientWithBasicAuth { public static void main(String args[]) { String host = "10.104.203.166";
int port = ;
String URI = "http://localhost/rest/channel/receipt"; // 创建HttpClientBuilder
httpClientBuilder httpClientBuilder = HttpClientBuilder.create();
// 设置BasicAuth
CredentialsProvider provider = new BasicCredentialsProvider();
// Create the authentication scope
AuthScope scope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM);
// Create credential pair,在此处填写用户名和密码
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("root", "superuser");
// Inject the credentials
provider.setCredentials(scope, credentials);
// Set the default credentials provider
httpClientBuilder.setDefaultCredentialsProvider(provider);
// HttpClient
CloseableHttpClient closeableHttpClient = httpClientBuilder.build(); String result = "";
HttpGet httpGet = null;
HttpResponse httpResponse = null;
HttpEntity entity = null;
httpGet = new HttpGet("http://"+host+URI);
try {
httpResponse = closeableHttpClient.execute(httpGet);
entity = httpResponse.getEntity();
if( entity != null ){
result = EntityUtils.toString(entity);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} // 关闭连接
closeableHttpClient.close(); //
System.out.println(result); }
}
方式三.
import java.io.IOException; import net.sf.json.JSONObject;
import net.spring.model.User; import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.junit.Test; public class Client {
@Test
public void HttpPostData() {
try {
HttpClient httpclient = new DefaultHttpClient();
String uri = "http://localhost:8080/springMVC/user/getUserByName";
HttpPost httppost = new HttpPost(uri);
//添加http头信息
httppost.addHeader("Authorization", "your token"); //认证token
httppost.addHeader("Content-Type", "application/json");
httppost.addHeader("User-Agent", "imgfornote");
JSONObject obj = new JSONObject();
obj.put("name", "cwh");
httppost.setEntity(new StringEntity(obj.toString()));
HttpResponse response;
response = httpclient.execute(httppost);
//检验状态码,如果成功接收数据
int code = response.getStatusLine().getStatusCode();
System.out.println(code+"code");
if (code == 200) {
String rev = EntityUtils.toString(response.getEntity());//返回json格式: {"id": "","name": ""}
obj= JSONObject.fromObject(rev); User user = (User)JSONObject.toBean(obj,User.class);
System.out.println("返回数据==="+user.toString());
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
java 发送带Basic Auth认证的http post请求实例代码的更多相关文章
- java 发送带Basic Auth认证的http post请求
构造http header private static final String URL = "url"; private static final String APP_KEY ...
- 精讲RestTemplate第9篇-如何通过HTTP Basic Auth认证
本文是精讲RestTemplate第9篇,前篇的blog访问地址如下: 精讲RestTemplate第1篇-在Spring或非Spring环境下如何使用 精讲RestTemplate第2篇-多种底层H ...
- java发送带附件的邮件
/** * java发送带附件的邮件 * 周枫 * 2013.8.10 */ package com.dsideal.Util; import javax.mail.*; import javax.m ...
- iOS AFNetWorking下得Basic Auth认证请求方式
我新入职了一家公司,做了一个项目,服务器的大哥说他采用的是Basic Auth认证请求方式,一般我们用的都是OAuth的认证方式,下面我们就对比一下这两种认证方式 百度百科得到如下 Basic Aut ...
- Http basic Auth 认证方式帮助类
BasicAuthenticationUtil import java.io.IOException; import java.security.MessageDigest; import javax ...
- ios开发使用Basic Auth 认证方式
http://blog.csdn.net/joonchen111/article/details/48447813 我们app的开发通常有2种认证方式 一种是Basic Auth,一种是OAuth ...
- Etcd安全配置之Basic Auth认证
<中小团队落地配置中心详解>文章中我们介绍了如何基于Etcd+Confd构建配置中心,最后提到Etcd的安全问题时说了可以使用账号密码认证以达到安全访问的目的,究竟该如何开启认证以及怎么设 ...
- HTTP Basic auth认证
Basic 概述 Basic 认证是HTTP 中非常简单的认证方式,因为简单,所以不是很安全,不过仍然非常常用. 当一个客户端向一个需要认证的HTTP服务器进行数据请求时,如果之前没有认证过,HTTP ...
- Java发送带附件的QQ邮箱
由于腾讯公司给QQ邮箱增加了一个授权码的密码保护,导致之前网上很多代码都不能用,于是就自己敲了一份demo. 注意在密码那里可能需要授权码,具体设置:http://service.mail.qq.co ...
随机推荐
- 【SQL Sever】安装过程
下载了sql sever,如下: 首先把iso解压,如下: 1.点击 2.打开页面后 3. 接下来直接下一步下一步 完成之后,需要重启计算机才能使用! 4. 重启之后,进入配置工具 将所有的端口号更改 ...
- DEBUG : Eclipse Debug 时出现 Cannot connect to VM select failed错误
Eclipse在执行Debug操作时, 出现“Eclipse Debug 时出现 "Cannot connect to VM select failed"”错误, 在网上查找该错误 ...
- 给ul下的li加click时间
$('.province ul li').click(function() {//方法 });
- 【转载】Java NIO学习 & NIO BIO AIO 比较
可以参考这个页面: http://www.iteye.com/magazines/132-Java-NIO (下面这个页面也有) http://ifeve.com/overview/ 另,在这篇文章里 ...
- BS中保存参数
开发中经常需要将值存起来,当点击某一项时以便知道点击了哪一项. 一:应用JS页面跳转(牛腩中讲到) HTML: <td class="txt c"><a href ...
- 【笔记】探索js 的this 对象 (第三部分)
了解完函数的调用区域是如何影响this 对象的,还有this 的各种绑定方式以及各种绑定方式的优先级后 最后一部分,来了解一下this 的一些例外情况 1.被忽略的this 例如在使用bind 方法时 ...
- Java开发岗位面试题归类---怎么好好的准备面试,也算是发展学习方向
转载:http://blog.csdn.net/qq_27093465/article/details/52181860 一.Java基础 1. String类为什么是final的. 自己找的参考答案 ...
- MongoDB数据库设计中6条重要的经验法则
Part 1 原文:6 Rules of Thumb for MongoDB Schema Design: Part 1 By William Zola, Lead Technical Support ...
- 记一次MySQL找回用户数据
事情经过 有天,我们公司外区的一个销售C说他8月3号以前的工作流记录找不到了.问清缘由,原来是更新了微信号(我们公司的工作流是基于企业微信开发的).经过分析,微信号和流程数据并没什么关系,所以初步得出 ...
- AFNetworking 文件上传Data,File图片,文件等上传
一:AFNetworking的文件上传: 主要几个以下类似 - (BOOL)appendPartWithFileURL:(NSURL *)fileURL name:(NSString *)name e ...