HttpClient示例_第1頁(yè)
HttpClient示例_第2頁(yè)
HttpClient示例_第3頁(yè)
HttpClient示例_第4頁(yè)
HttpClient示例_第5頁(yè)
已閱讀5頁(yè),還剩3頁(yè)未讀, 繼續(xù)免費(fèi)閱讀

下載本文檔

版權(quán)說(shuō)明:本文檔由用戶(hù)提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)

文檔簡(jiǎn)介

1、HttpClient示例一、HttpClient簡(jiǎn)介HttpClient 是 Apache Jakarta Common 下的子項(xiàng)目,用來(lái)提供高效的、最新的、功能豐富的支持 HTTP 協(xié)議的客戶(hù)端編程工具包,并且它支持 HTTP 協(xié)議最新的版本和建議。HttpClient 已經(jīng)應(yīng)用在很多的項(xiàng)目中,比如 Apache Jakarta 上很著名的另外兩個(gè)開(kāi)源項(xiàng)目 Cactus 和 HTMLUnit 都使用了 HttpClient?,F(xiàn)在HttpClient最新版本為 HttpClient 4.3.二、HttpClient特性基于標(biāo)準(zhǔn),純凈的java語(yǔ)言.實(shí)現(xiàn)了Http1.0和Http1.1以可擴(kuò)展的

2、面向?qū)ο蟮慕Y(jié)構(gòu)實(shí)現(xiàn)了Http全部的方法 (GET, POST, PUT, DELETE, HEAD, OPTIONS, and TRACE).支持HTTPS協(xié)議.通過(guò)Http代理建立透明的連接.利用CONNECT 方法通過(guò)Http代理建立隧道的https連接.Basic, Digest, NTLMv1, NTLMv2, NTLM2 Session, SNPNEGO/Kerberos 認(rèn)證方案.插件式的自定義認(rèn)證方案.便攜可靠的套接字工廠(chǎng)使它更容易的使用第三方解決方案.連接管理器支持多線(xiàn)程應(yīng)用.支持設(shè)置最大連接數(shù),同時(shí)支持設(shè)置每個(gè)主機(jī)的最大連接數(shù).發(fā)現(xiàn)并關(guān)閉過(guò)期的連接.Automatic Coo

3、kie handling for reading Set-Cookie: headers from the server and sending them back out in a Cookie: header when appropriate.插件式的自定義Cookie策略.Request output streams to avoid buffering any content body by streaming directly to the socket to the server.Response input streams to efficiently read the resp

4、onse body by streaming directly from the socket to the server.在http1.0和http1.1中利用KeepAlive保持持久連接.直接獲取服務(wù)器發(fā)送的response code和 headers.設(shè)置連接超時(shí)的能力.實(shí)驗(yàn)性的支持http1.1 response caching.源代碼基于Apache License 可免費(fèi)獲取.三、詳細(xì)講解這里為了更好的理解,新建了一個(gè)java se的工程,如下圖所示 HttpClientTest類(lèi)package com.yulore.httpproxy; import java.io.

5、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.Unrec

6、overableKeyException; import java.security.cert.CertificateException; import java.util.ArrayList; import java.util.List; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.ParseException; import org.apache.http.client.

7、ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.conn.scheme.Scheme; import org.apache.http.conn.ssl.SSLS

8、ocketFactory; import org.apache.http.impl.client.DefaultHttpClient; 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 */ private void ssl() DefaultHtt

9、pClient httpclient = new DefaultHttpClient(); 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".toCharArra

10、y(); catch (CertificateException e) e.printStackTrace(); finally try instream.close(); catch (Exception ignore) / 穿件Socket工廠(chǎng),將trustStore注入 SSLSocketFactory socketFactory = new SSLSocketFactory(trustStore); / 創(chuàng)建Scheme Scheme sch = new Scheme("https", 8443, socketFactory); / 注冊(cè)Scheme httpcli

11、ent.getConnectionManager().getSchemeRegistry().register(sch); / 創(chuàng)建http請(qǐng)求(get方式) HttpGet httpget = new HttpGet( "https:/localhost:8443/myDemo/Ajax/serivceJ.action"); System.out.println("executing request" + httpget.getRequestLine(); HttpResponse response = httpclient.execute(httpg

12、et); HttpEntity entity = response.getEntity(); System.out.println("-"); System.out.println(response.getStatusLine(); if (entity != null) System.out.println("Response content length: " + entity.getContentLength(); String ss = EntityUtils.toString(entity); System.out.println(ss); E

13、ntityUtils.consume(entity); catch (ParseException e) e.printStackTrace(); catch (IOException e) e.printStackTrace(); catch (KeyManagementException e) e.printStackTrace(); catch (UnrecoverableKeyException e) e.printStackTrace(); catch (NoSuchAlgorithmException e) e.printStackTrace(); catch (KeyStoreE

14、xception e) e.printStackTrace(); finally httpclient.getConnectionManager().shutdown(); /* * post方式提交表單(模擬用戶(hù)登錄請(qǐng)求) */ private void postForm() / 創(chuàng)建默認(rèn)的httpClient實(shí)例. HttpClient httpclient = new DefaultHttpClient(); / 創(chuàng)建httppost HttpPost httppost = new HttpPost( "http:/localhost:8080/myDemo/Ajax/seri

15、vceJ.action"); / 創(chuàng)建參數(shù)隊(duì)列 List<NameValuePair> formparams = new ArrayList<NameValuePair>(); formparams.add(new BasicNameValuePair("username", "admin"); formparams.add(new BasicNameValuePair("password", "123456"); UrlEncodedFormEntity uefEntity; t

16、ry uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8"); httppost.setEntity(uefEntity); System.out.println("executing request " + httppost.getURI(); HttpResponse response; response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); if (entity != null)

17、System.out.println("-"); System.out.println("Response content: " + EntityUtils.toString(entity, "UTF-8"); System.out.println("-"); catch (ClientProtocolException e) e.printStackTrace(); catch (UnsupportedEncodingException e1) e1.printStackTrace(); catch (IOExc

18、eption e) e.printStackTrace(); finally / 關(guān)閉連接,釋放資源 httpclient.getConnectionManager().shutdown(); /* * 發(fā)送 post請(qǐng)求訪(fǎng)問(wèn)本地應(yīng)用并根據(jù)傳遞參數(shù)不同返回不同結(jié)果 */ private void post() / 創(chuàng)建默認(rèn)的httpClient實(shí)例. HttpClient httpclient = new DefaultHttpClient(); / 創(chuàng)建httppost HttpPost httppost = new HttpPost( "http:/localhost:8080/

19、myDemo/Ajax/serivceJ.action"); / 創(chuàng)建參數(shù)隊(duì)列 List<NameValuePair> formparams = new ArrayList<NameValuePair>(); formparams.add(new BasicNameValuePair("type", "house"); UrlEncodedFormEntity uefEntity; try uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8"

20、); httppost.setEntity(uefEntity); System.out.println("executing request " + httppost.getURI(); HttpResponse response; response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); if (entity != null) System.out.println("-"); System.out.println("Response

21、content: " + EntityUtils.toString(entity, "UTF-8"); System.out.println("-"); catch (ClientProtocolException e) e.printStackTrace(); catch (UnsupportedEncodingException e1) e1.printStackTrace(); catch (IOException e) e.printStackTrace(); finally / 關(guān)閉連接,釋放資源 httpclient.getConn

22、ectionManager().shutdown(); /* * 發(fā)送 get請(qǐng)求 */ private void get() HttpClient httpclient = new DefaultHttpClient(); try / 創(chuàng)建httpget. HttpGet httpget = new HttpGet(" System.out.println("executing request " + httpget.getURI(); / 執(zhí)行g(shù)et請(qǐng)求. HttpResponse response = httpclient.execute(httpget);

23、 / 獲取響應(yīng)實(shí)體 HttpEntity entity = response.getEntity(); System.out.println("-"); / 打印響應(yīng)狀態(tài) System.out.println(response.getStatusLine(); if (entity != null) / 打印響應(yīng)內(nèi)容長(zhǎng)度 System.out.println("Response content length: " + entity.getContentLength(); / 打印響應(yīng)內(nèi)容 System.out.println("Response

24、 content: " + EntityUtils.toString(entity); System.out.println("-"); catch (ClientProtocolException e) e.printStackTrace(); catch (ParseException e) e.printStackTrace(); catch (IOException e) e.printStackTrace(); finally / 關(guān)閉連接,釋放資源 httpclient.getConnectionManager().shutdown(); 詳細(xì)信息請(qǐng)看

25、程序中的注釋注意事項(xiàng)JUnit運(yùn)行測(cè)試時(shí)報(bào)錯(cuò),錯(cuò)誤日志信息如下:java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactoryat org.apache.http.impl.client.AbstractHttpClient.<init>(AbstractHttpClient.java:182)at org.apache.http.impl.client.DefaultHttpClient.<init>(DefaultHttpClient.java:150)at com.yulore.httpp

26、roxy.HttpClientTest.get(HttpClientTest.java:180)at com.yulore.httpproxy.HttpClientTest.jUnitTest(HttpClientTest.java:36)at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)at sun.reflect.DelegatingMethodAccesso

27、rImpl.invoke(DelegatingMethodAccessorImpl.java:25)at java.lang.reflect.Method.invoke(Method.java:597)at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)at ernal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)at org.junit.runners.model

28、.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)at ernal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)at org.junit.runners.BlockJUnit4ClassRunner.runNotIgnored(BlockJUnit4ClassRunner.java:79)at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4Clas

29、sRunner.java:71)at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:49)at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)at org.junit.runners.P

溫馨提示

  • 1. 本站所有資源如無(wú)特殊說(shuō)明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶(hù)所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁(yè)內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒(méi)有圖紙預(yù)覽就沒(méi)有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫(kù)網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶(hù)上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶(hù)上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
  • 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶(hù)因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。

最新文檔

評(píng)論

0/150

提交評(píng)論