package com.test;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.util.ArrayList;
import java.util.List;
import javax.net.ssl.SSLContext;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.junit.Test;
public class HttpClientTest {
@Test
public void jUnitTest() {
get();
}
/**
* HttpClient連接SSL
*/
public void ssl() {
CloseableHttpClient httpclient = null;
try {
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
FileInputStream instream = new FileInputStream(new File("d:\\tomcat.keystore"));
try {
// 加載keyStore d:\\tomcat.keystore
trustStore.load(instream, "123456".toCharArray());
} catch (CertificateException e) {
e.printStackTrace();
} finally {
try {
instream.close();
} catch (Exception ignore) {
}
}
// 相信自己的CA和所有自簽名的證書
SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()).build();
// 只允許使用TLSv1協議
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" }, null,
SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
// 創建http請求(get方式)
HttpGet httpget = new HttpGet("https://localhost:8443/myDemo/Ajax/serivceJ.action");
System.out.println("executing request" + httpget.getRequestLine());
CloseableHttpResponse response = httpclient.execute(httpget);
try {
HttpEntity entity = response.getEntity();
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
if (entity != null) {
System.out.println("Response content length: " + entity.getContentLength());
System.out.println(EntityUtils.toString(entity));
EntityUtils.consume(entity);
}
} finally {
response.close();
}
} catch (ParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
} finally {
if (httpclient != null) {
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* post方式提交表單(模擬用戶登錄請求)
*/
public void postForm() {
// 創建默認的httpClient實例.
CloseableHttpClient httpclient = HttpClients.createDefault();
// 創建httppost
HttpPost httppost = new HttpPost("http://localhost:8080/myDemo/Ajax/serivceJ.action");
// 創建參數隊列
List<namevaluepair> formparams = new ArrayList<namevaluepair>();
formparams.add(new BasicNameValuePair("username", "admin"));
formparams.add(new BasicNameValuePair("password", "123456"));
UrlEncodedFormEntity uefEntity;
try {
uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
httppost.setEntity(uefEntity);
System.out.println("executing request " + httppost.getURI());
CloseableHttpResponse response = httpclient.execute(httppost);
try {
HttpEntity entity = response.getEntity();
if (entity != null) {
System.out.println("--------------------------------------");
System.out.println("Response content: " + EntityUtils.toString(entity, "UTF-8"));
System.out.println("--------------------------------------");
}
} finally {
response.close();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 關閉連接,釋放資源
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 發送 post請求訪問本地應用並根據傳遞參數不同返回不同結果
*/
public void post() {
// 創建默認的httpClient實例.
CloseableHttpClient httpclient = HttpClients.createDefault();
// 創建httppost
HttpPost httppost = new HttpPost("http://localhost:8080/myDemo/Ajax/serivceJ.action");
// 創建參數隊列
List<namevaluepair> formparams = new ArrayList<namevaluepair>();
formparams.add(new BasicNameValuePair("type", "house"));
UrlEncodedFormEntity uefEntity;
try {
uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
httppost.setEntity(uefEntity);
System.out.println("executing request " + httppost.getURI());
CloseableHttpResponse response = httpclient.execute(httppost);
try {
HttpEntity entity = response.getEntity();
if (entity != null) {
System.out.println("--------------------------------------");
System.out.println("Response content: " + EntityUtils.toString(entity, "UTF-8"));
System.out.println("--------------------------------------");
}
} finally {
response.close();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 關閉連接,釋放資源
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 發送 get請求
*/
public void get() {
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
// 創建httpget.
HttpGet httpget = new HttpGet("http://www.baidu.com/");
System.out.println("executing request " + httpget.getURI());
// 執行get請求.
CloseableHttpResponse response = httpclient.execute(httpget);
try {
// 獲取響應實體
HttpEntity entity = response.getEntity();
System.out.println("--------------------------------------");
// 打印響應狀態
System.out.println(response.getStatusLine());
if (entity != null) {
// 打印響應內容長度
System.out.println("Response content length: " + entity.getContentLength());
// 打印響應內容
System.out.println("Response content: " + EntityUtils.toString(entity));
}
System.out.println("------------------------------------");
} finally {
response.close();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 關閉連接,釋放資源
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 上傳文件
*/
public void upload() {
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
HttpPost httppost = new HttpPost("http://localhost:8080/myDemo/Ajax/serivceFile.action");
FileBody bin = new FileBody(new File("F:\\image\\sendpix0.jpg"));
StringBody comment = new StringBody("A binary file of some kind", ContentType.TEXT_PLAIN);
HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("bin", bin).addPart("comment", comment).build();
httppost.setEntity(reqEntity);
System.out.println("executing request " + httppost.getRequestLine());
CloseableHttpResponse response = httpclient.execute(httppost);
try {
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
System.out.println("Response content length: " + resEntity.getContentLength());
}
EntityUtils.consume(resEntity);
} finally {
response.close();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}</namevaluepair></namevaluepair></namevaluepair></namevaluepair>
HttpClient使用詳解
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章
企業微信開發整理彙總
铁头哇
2020-07-07 22:48:59
最近項目用到Dubbo框架,臨時抱佛腳分享一下共探討
Huang Zhenwei
2020-07-05 07:27:40
Android 關於SP讀取與存儲正確打開方式?
KdanMin
2020-06-29 15:35:41
阿里雲短信服務(新版)開發——Thinkphp
卖女孩的小火柴~
2020-06-23 07:44:51
Java Http接口簽名驗籤實例---東科教育
猿人榉
2020-06-10 03:51:39
Swagger開發(含文件上傳)和文檔導出
名字全都被占用了
2020-05-12 02:18:21
公衆平臺測試帳號開發全流程第9篇-模板消息
huang_zd
2020-02-23 07:10:09
cxf+spring發佈webservice接口及接口的調用
Huang Zhenwei
2020-02-22 00:22:04
客戶端使用js拼接二維數組,提交到服務器端,服務器端無法接收?
秋豆角之藤
2020-02-21 16:19:17
關於初級程序員職場如何提升技能的幾點建議?
KdanMin
2020-02-20 19:34:03
長整型Long返回到前端,js出現精度丟失怎麼辦
layveen
2019-12-15 14:03:32
Web篇--java編寫接口爲外部提供服務技術選擇
钢铁侠2
2019-04-04 23:13:45
嘗試理解SOAP與REST和RESTful
让你为我而骄傲
2018-11-04 11:05:45
Mybatis Generator最完整配置詳解
Android小码农
2018-10-27 10:22:23