转-HTTPClient调用https请求,通过基本认证用户名密码(Basic Auth)
生活随笔
收集整理的這篇文章主要介紹了
转-HTTPClient调用https请求,通过基本认证用户名密码(Basic Auth)
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
轉(zhuǎn)自: https://blog.csdn.net/qq_27605885/article/details/79131483
本文來源是Apache官網(wǎng)例子:http://hc.apache.org/httpcomponents-client-4.5.x/httpclient/examples/org/apache/http/examples/client/ClientAuthentication.java
之前找過很多博客上的例子發(fā)現(xiàn)都不對,后來還是去官網(wǎng)找。事實證明官網(wǎng)絕對比博客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請求,直接發(fā)送json格式的作為參數(shù)傳到服務(wù)器 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"));總結(jié)
以上是生活随笔為你收集整理的转-HTTPClient调用https请求,通过基本认证用户名密码(Basic Auth)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: win10 swapfile.sys怎么
- 下一篇: 转:字符串和编码