HttpClient 在Java項目中的應用詳解。本站提示廣大學習愛好者:(HttpClient 在Java項目中的應用詳解)文章只能為提供參考,不一定能成為您想要的結果。以下是HttpClient 在Java項目中的應用詳解正文
Http協定的主要性信任不消我多說了,HttpClient比擬傳統JDK自帶的URLConnection,增長了易用性和靈巧性(詳細差別,往後我們再評論辯論),它不只是客戶端發送Http要求變得輕易,並且也便利了開辟人員測試接口(基於Http協定的),即進步了開辟的效力,也便利進步代碼的硬朗性。是以闇練控制HttpClient是很主要的?內容,控制HttpClient後,信任關於Http協定的懂得會加倍深刻。
1、簡介
HttpClient是Apache Jakarta Common下的子項目,用來供給高效的、最新的、功效豐碩的支撐HTTP協定的客戶端編程對象包,而且它支撐HTTP協定最新的版本和建議。HttpClient曾經運用在許多的項目中,好比Apache Jakarta上很有名的別的兩個開源項目Cactus和HTMLUnit都應用了HttpClient。
下載地址: http://hc.apache.org/downloads.cgi
2、特征
1. 基於尺度、純潔的java說話。完成了Http1.0和Http1.1
2. 以可擴大的面向對象的構造完成了Http全體的辦法(GET, POST, PUT, DELETE, HEAD, OPTIONS, and TRACE)。
3. 支撐HTTPS協定。
4. 經由過程Http署理樹立通明的銜接。
5. 應用CONNECT辦法經由過程Http署理樹立地道的https銜接。
6. Basic, Digest, NTLMv1, NTLMv2, NTLM2 Session, SNPNEGO/Kerberos認證計劃。
7. 插件式的自界說認證計劃。
8. 便攜靠得住的套接字工場使它更輕易的應用第三方處理計劃。
9. 銜接治理器支撐多線程運用。支撐設置最年夜銜接數,同時支撐設置每一個主機的最年夜銜接數,發明並封閉過時的銜接。
10. 主動處置Set-Cookie中的Cookie。
11. 插件式的自界說Cookie戰略。
12. Request的輸入流可以免流中內容直接緩沖到socket辦事器。
13. Response的輸出流可以有用的從socket辦事器直接讀取響應內容。
14. 在http1.0和http1.1中應用KeepAlive堅持耐久銜接。
15. 直接獲得辦事器發送的response code和 headers。
16. 設置銜接超時的才能。
17. 試驗性的支撐http1.1 response caching。
18. 源代碼基於Apache License 可收費獲得。
3、應用辦法
應用HttpClient發送要求、吸收呼應很簡略,普通須要以下幾步便可。
1. 創立HttpClient對象。
2. 創立要求辦法的實例,並指定要求URL。假如須要發送GET要求,創立HttpGet對象;假如須要發送POST要求,創立HttpPost對象。
3. 假如須要發送要求參數,可挪用HttpGet、HttpPost配合的setParams(HetpParams params)辦法來添加要求參數;關於HttpPost對象而言,也可挪用setEntity(HttpEntity entity)辦法來設置要求參數。
4. 挪用HttpClient對象的execute(HttpUriRequest request)發送要求,該辦法前往一個HttpResponse。
5. 挪用HttpResponse的getAllHeaders()、getHeaders(String name)等辦法可獲得辦事器的呼應頭;挪用HttpResponse的getEntity()辦法可獲得HttpEntity對象,該對象包裝了辦事器的呼應內容。法式可經由過程該對象獲得辦事器的呼應內容。
6. 釋放銜接。不管履行辦法能否勝利,都必需釋放銜接
4、實例
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.百度.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>
本實例是采取HttpClient4.3最新版本。該版本與之前的代碼寫法作風相差較年夜,年夜家多留心下。