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 ...
随机推荐
- 可添加头部尾部RecyclerView,很帅哦~
WrapRecyclerView 是一个可以添加头部和尾部的RecyclerView,并且提供了一个 WrapAdapter, 它可以让你轻松为 RecyclerView 添加头部和尾部. 示例中 ...
- javascript 中contentWindow和 frames和iframe之间通信
iframe父子兄弟之间通过jquery传值(contentWindow && parent),iframe的调用包括以下几个方面:(调用包含html dom,js全局变量,js方法) ...
- BrowserSync-多浏览器测试工具
阅读目录 自动刷新 介绍BrowserSync BrowserSync具体使用 BrowserSync配合gulp 自动刷新 自动刷新,顾名思义,就是不用我们去F5刷新.假设有一天我们写代码,只需要c ...
- java实现 tf-idf
1.前言 TF-IDF(term frequency–inverse document frequency)是一种用于信息检索与数据挖掘的常用加权技术.TF意思是词频(Term Frequency), ...
- 【架构】Twitter高性能RPC框架Finagle介绍
Twitter的RPC框架Finagle简介 Finagle是Twitter基于Netty开发的支持容错的.协议无关的RPC框架,该框架支撑了Twitter的核心服务.来自Twitter的软件工程师J ...
- /dev/null 的含义和用途
/dev/null 代表空设备文件,它等价于一个仅仅写文件,全部写入它的内容都会永远丢失.而尝试从它那儿读取内容则什么也读不到. 0:表示键盘输入(stdin) 1:表示标准输出(stdout),系统 ...
- redis学习笔记——初始化
初始化服务器状态结构 redis中一个最重要的数据结构是redis_server,会创建一个这个结构的全局变量server,初始化服务器的第一步就是创建一个struct redisServer类型的实 ...
- Win7开机提示group policy client无法登陆怎么办
1 开机按F8,进入安全模式 2 进入系统之后运行注册表,定位到HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Prof ...
- RTP Tools
RTP Tools (Version 1.20) https://wiki.wireshark.org/RTP_statistics Here is a small example: Install ...
- 算法笔记_051:荷兰国旗问题(Java)
目录 1 问题描述 2 解决方案 1 问题描述 现有n个红白蓝三种不同颜色的小球,乱序排列在一起,请通过两两交换任意两个球,使得从左至右的球依次为红球.白球.蓝球.这个问题之所以叫荷兰国旗,是因为 ...