构造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请求实例代码的更多相关文章

  1. java 发送带Basic Auth认证的http post请求

    构造http header private static final String URL = "url"; private static final String APP_KEY ...

  2. 精讲RestTemplate第9篇-如何通过HTTP Basic Auth认证

    本文是精讲RestTemplate第9篇,前篇的blog访问地址如下: 精讲RestTemplate第1篇-在Spring或非Spring环境下如何使用 精讲RestTemplate第2篇-多种底层H ...

  3. java发送带附件的邮件

    /** * java发送带附件的邮件 * 周枫 * 2013.8.10 */ package com.dsideal.Util; import javax.mail.*; import javax.m ...

  4. iOS AFNetWorking下得Basic Auth认证请求方式

    我新入职了一家公司,做了一个项目,服务器的大哥说他采用的是Basic Auth认证请求方式,一般我们用的都是OAuth的认证方式,下面我们就对比一下这两种认证方式 百度百科得到如下 Basic Aut ...

  5. Http basic Auth 认证方式帮助类

    BasicAuthenticationUtil import java.io.IOException; import java.security.MessageDigest; import javax ...

  6. ios开发使用Basic Auth 认证方式

    http://blog.csdn.net/joonchen111/article/details/48447813 我们app的开发通常有2种认证方式   一种是Basic Auth,一种是OAuth ...

  7. Etcd安全配置之Basic Auth认证

    <中小团队落地配置中心详解>文章中我们介绍了如何基于Etcd+Confd构建配置中心,最后提到Etcd的安全问题时说了可以使用账号密码认证以达到安全访问的目的,究竟该如何开启认证以及怎么设 ...

  8. HTTP Basic auth认证

    Basic 概述 Basic 认证是HTTP 中非常简单的认证方式,因为简单,所以不是很安全,不过仍然非常常用. 当一个客户端向一个需要认证的HTTP服务器进行数据请求时,如果之前没有认证过,HTTP ...

  9. Java发送带附件的QQ邮箱

    由于腾讯公司给QQ邮箱增加了一个授权码的密码保护,导致之前网上很多代码都不能用,于是就自己敲了一份demo. 注意在密码那里可能需要授权码,具体设置:http://service.mail.qq.co ...

随机推荐

  1. Laravel简⃣单⃣的⃣路⃣由⃣

    在⃣routes.php文⃣件⃣中⃣写⃣如⃣下⃣几⃣个⃣函⃣数⃣: Route::get('/', function () { return view('welcome'); }); // 获⃣取⃣a ...

  2. SpringMVC中拦截器的使用

    什么是拦截器 拦截器通常一般指的是通过拦截从浏览器发往服务器的一些请求来完成某些功能的一段程序代码一般在一个请求发生之前,发生时,发生后我们都可以对请求进行拦截 拦截器可以做什么 拦截器可以用于权限验 ...

  3. IngressController的session stick问题

    周末爬坑,IngressController恢复因为镜像下载和版本问题折腾一下午,晚上终于折腾出个眉目. 首先,在Kubernetes的service中是可以设置Session Affinity的.例 ...

  4. static_cast ,reinterpret_cast

    用法:static_cast < type-id > ( expression ) 该运算符把expression转换为type-id类型,但没有运行时类型检查来保证转换的安全性.它主要有 ...

  5. 五、Springboot 之 自定义配置文件及读取配置文件

    说明:建议所有的类应该与spring-boot启动程序同级,不如扫描不到 1.核心配置文件是指在resources根目录下的application.properties或application.yml ...

  6. 移动APP安全在渗透测试中的应用

    安全爱好者研究的往往是app的本地安全,比如远控.应用破解.信息窃取等等,大多人还没有关注到app服务端的安全问题,于是在这块的安全漏洞非常多. 移动app大多通过web api服务的方式跟服务端交互 ...

  7. scrapy-splash抓取动态数据例子六

    一.介绍 本例子用scrapy-splash抓取中广互联网站给定关键字抓取咨询信息. 给定关键字:打通:融合:电视 抓取信息内如下: 1.资讯标题 2.资讯链接 3.资讯时间 4.资讯来源 二.网站信 ...

  8. 从外部重置一个运行中consumer group的消费进度

    对于0.10.1以上版本的kafka, 如何从外部重置一个运行中的consumer group的进度呢?比如有一个控制台,可以主动重置任意消费组的消费进度重置到12小时之前, 而用户的程序可以保持运行 ...

  9. 【云计算】OpenStack项目全面介绍

    关于OpenStack孵化项目trove(DBaaS)之我见:http://blog.csdn.net/ddl007/article/details/17253751 OpenStack Trove将 ...

  10. idea autoscroll from source