HTTPClient调用https请求,通过基本认证用户名密码(Basic Auth)
2018-01-22 18:42
627 查看
本文来源是Apache官网例子:http://hc.apache.org/httpcomponents-client-4.5.x/httpclient/examples/org/apache/http/examples/client/ClientAuthentication.java之前找过很多博客上的例子发现都不对,后来还是去官网找。事实证明官网绝对比博客k例子:
public static void http() throws Exception { JSONObject obj = new JSONObject(); obj.put("param", "paramValue"); CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(userName, password)); CloseableHttpClient createDefault = HttpClients.custom() .setDefaultCredentialsProvider(credsProvider) .build(); HttpPost post = new HttpPost(url); StringEntity entity = new StringEntity(obj.toString(),"utf-8"); entity.setContentEncoding("UTF-8"); entity.setContentType("application/json"); post.setEntity(entity); CloseableHttpResponse result = createDefault.execute(post); int statusCode = result.getStatusLine().getStatusCode(); System.out.println(statusCode); System.out.println("result:" + EntityUtils.toString(result.getEntity())); }
//下面是正常http请求,直接发送json格式的作为参数传到服务器
HttpPost post = new HttpPost(url);//post.setHeader("Content-Type","application/json;charset=utf-8");StringEntity entity = new StringEntity(obj.toString(),"utf-8");entity.setContentEncoding("UTF-8");entity.setContentType("application/json");post.setEntity(entity);CloseableHttpClient createDefault = HttpClients.createDefault();CloseableHttpResponse result = createDefault.execute(post);String responseMsg = EntityUtils.toString(result.getEntity(),"UTF-8"));
相关文章推荐
- java 通过httpclient调用https 的webapi
- 使用powershell通过配置文件config调用wcf(含用户名密码认证)
- 通过4.4httpclient访问http和调用https
- common-httpclient 用户名密码认证示例
- Java 通过HttpClient 带证书方式请求Https协议网站 (Post方式带xml文档,Get以及Delete方式)
- HttpClient请求https认证问题
- java 通过httpclient调用https 的webapi
- httpclient用户名密码认证示例
- Android支持https的处理方式1----httpclient请求https的处理方式
- java 通过httpClient调用后端逻辑或者下载附件
- Java爬虫(七)- httpClient进阶: https 和 证书认证(讲故事篇)
- nginx让用户通过用户名密码认证访问web页面
- nginx让用户通过用户名密码认证访问web页面
- ASIHTTPRequest实现https双向认证请求
- Android网络请求操作httpurlconnection和httpclient基本使用
- Cocoa 通过http请求调用WCF服务
- HttpClient(4.3.5)请求数据,支持https
- ASIHTTPRequest实现https双向认证请求
- HttpClient 发送 HTTP、HTTPS 请求的简单封装
- 通过httpClient发送json格式数据请求