亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

Home php教程 php手冊 Cookies,SSL,httpclient的多線程處理,HTTP方法

Cookies,SSL,httpclient的多線程處理,HTTP方法

Jun 21, 2016 am 09:15 AM
cookie httpclient new quot

client|cookie|cookies|多線程


— 作者 sunggsun @ 20:26





8、Cookies

   HttpClient能自動管理cookie,包括允許服務(wù)器設(shè)置cookie并在需要的時候自動將cookie返回服務(wù)器,它也支持手工設(shè)置cookie后發(fā)送到服務(wù)器端。不幸的是,對如何處理cookie,有幾個規(guī)范互相沖突:Netscape Cookie 草案, RFC2109, RFC2965,而且還有很大數(shù)量的軟件商的cookie實現(xiàn)不遵循任何規(guī)范. 為了處理這種狀況,HttpClient提供了策略驅(qū)動的cookie管理方式。HttpClient支持的cookie規(guī)范有:

Netscape cookie草案,是最早的cookie規(guī)范,基于rfc2109。盡管這個規(guī)范與rc2109有較大的差別,這樣做可以與一些服務(wù)器兼容。

rfc2109,是w3c發(fā)布的第一個官方cookie規(guī)范。理論上講,所有的服務(wù)器在處理cookie(版本1)時,都要遵循此規(guī)范,正因如此,HttpClient將其設(shè)為默認(rèn)的規(guī)范。遺憾的是,這個規(guī)范太嚴(yán)格了,以致很多服務(wù)器不正確的實施了該規(guī)范或仍在作用Netscape規(guī)范。在這種情況下,應(yīng)使用兼容規(guī)范。

兼容性規(guī)范,設(shè)計用來兼容盡可能多的服務(wù)器,即使它們并沒有遵循標(biāo)準(zhǔn)規(guī)范。當(dāng)解析cookie出現(xiàn)問題時,應(yīng)考慮采用兼容性規(guī)范。

   RFC2965規(guī)范暫時沒有被HttpClient支持(在以后的版本為會加上),它定義了cookie版本2,并說明了版本1cookie的不足,RFC2965有意有久取代rfc2109.
  在HttpClient中,有兩種方法來指定cookie規(guī)范的使用,
HttpClient client = new HttpClient();
client.getState().setCookiePolicy(CookiePolicy.COMPATIBILITY);
這種方法設(shè)置的規(guī)范只對當(dāng)前的HttpState有效,參數(shù)可取值CookiePolicy.COMPATIBILITY,CookiePolicy.NETSCAPE_DRAFT或CookiePolicy.RFC2109。

System.setProperty("apache.commons.httpclient.cookiespec", "COMPATIBILITY");
此法指的規(guī)范,對以后每個新建立的HttpState對象都有效,參數(shù)可取值"COMPATIBILITY","NETSCAPE_DRAFT"或"RFC2109"。
  常有不能解析cookie的問題,但更換到兼容規(guī)范大都能解決。

  
9、使用HttpClient遇到問題怎么辦?


用一個瀏覽器訪問服務(wù)器,以確認(rèn)服務(wù)器應(yīng)答正常

如果在使代理,關(guān)掉代理試試

另找一個服務(wù)器來試試(如果運行著不同的服務(wù)器軟件更好)

檢查代碼是否按教程中講的思路編寫

設(shè)置log級別為debug,找出問題出現(xiàn)的原因

打開wiretrace,來追蹤客戶端與服務(wù)器的通信,以確實問題出現(xiàn)在什么地方

用telnet或netcat手工將信息發(fā)送到服務(wù)器,適合于猜測已經(jīng)找到了原因而進(jìn)行試驗時

將netcat以監(jiān)聽方式運行,用作服務(wù)器以檢查httpclient如何處理應(yīng)答的。

利用最新的httpclient試試,bug可能在最新的版本中修復(fù)了

向郵件列表求幫助

向bugzilla報告bug.

  

10、SSL

  借助Java Secure Socket Extension (JSSE),HttpClient全面支持Secure Sockets Layer (SSL)或IETF Transport Layer Security (TLS)協(xié)議上的HTTP。JSSE已經(jīng)jre1.4及以后的版本中,以前的版本則需要手工安裝設(shè)置,具體過程參見Sun網(wǎng)站或本學(xué)習(xí)筆記。
  HttpClient中使用SSL非常簡單,參考下面兩個例子:
HttpClient httpclient = new HttpClient();
GetMethod httpget = new GetMethod("https://www.verisign.com/");
httpclient.executeMethod(httpget);
System.out.println(httpget.getStatusLine().toString());
,如果通過需要授權(quán)的代理,則如下:
HttpClient httpclient = new HttpClient();
httpclient.getHostConfiguration().setProxy("myproxyhost", 8080);
httpclient.getState().setProxyCredentials("my-proxy-realm", " myproxyhost",
new UsernamePasswordCredentials("my-proxy-username", "my-proxy-password"));
GetMethod httpget = new GetMethod("https://www.verisign.com/");
httpclient.executeMethod(httpget);
System.out.println(httpget.getStatusLine().toString());

  在HttpClient中定制SSL的步驟如下:

提供了一個實現(xiàn)了org.apache.commons.httpclient.protocol.SecureProtocolSocketFactory接口的socket factory。這個 socket factory負(fù)責(zé)打一個到服務(wù)器的端口,使用標(biāo)準(zhǔn)的或第三方的SSL函數(shù)庫,并進(jìn)行象連接握手等初始化操作。通常情況下,這個初始化操作在端口被創(chuàng)建時自動進(jìn)行的。

實例化一個org.apache.commons.httpclient.protocol.Protocol對象。創(chuàng)建這個實例時,需要一個合法的協(xié)議類型(如https),一個定制的socket factory,和一個默認(rèn)的端中號(如https的443端口).
Protocol myhttps = new Protocol("https", new MySSLSocketFactory(), 443);
然后,這個實例可被設(shè)置為協(xié)議的處理器。
HttpClient httpclient = new HttpClient();
httpclient.getHostConfiguration().setHost("www.whatever.com", 443, myhttps);
GetMethod httpget = new GetMethod("/");
httpclient.executeMethod(httpget);


通過調(diào)用Protocol.registerProtocol方法,將此定制的實例,注冊為某一特定協(xié)議的默認(rèn)的處理器。由此,可以很方便地定制自己的協(xié)議類型(如myhttps)。
Protocol.registerProtocol("myhttps",
new Protocol("https", new MySSLSocketFactory(), 9443));
...
HttpClient httpclient = new HttpClient();
GetMethod httpget = new GetMethod("myhttps://www.whatever.com/");
httpclient.executeMethod(httpget);
如果想用自己定制的處理器取代https默認(rèn)的處理器,只需要將其注冊為"https"即可。
Protocol.registerProtocol("https",
new Protocol("https", new MySSLSocketFactory(), 443));
HttpClient httpclient = new HttpClient();
GetMethod httpget = new GetMethod("https://www.whatever.com/");
httpclient.executeMethod(httpget);

  已知的限制和問題

持續(xù)的SSL連接在Sun的低于1.4JVM上不能工作,這是由于JVM的bug造成。

通過代理訪問服務(wù)器時,非搶先認(rèn)證( Non-preemptive authentication)會失敗,這是由于HttpClient的設(shè)計缺陷造成的,以后的版本中會修改。

  遇到問題的處理
  很多問題,特別是在jvm低于1.4時,是由jsse的安裝造成的。
  下面的代碼,可作為最終的檢測手段。

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.Socket;

import javax.net.ssl.SSLSocketFactory;

public class Test {

public static final String TARGET_HTTPS_SERVER = "www.verisign.com";
public static final int TARGET_HTTPS_PORT = 443;

public static void main(String[] args) throws Exception {

Socket socket = SSLSocketFactory.getDefault().
createSocket(TARGET_HTTPS_SERVER, TARGET_HTTPS_PORT);
try {
Writer out = new OutputStreamWriter(
socket.getOutputStream(), "ISO-8859-1");
out.write("GET / HTTP/1.1rn");
out.write("Host: " + TARGET_HTTPS_SERVER + ":" +
TARGET_HTTPS_PORT + "rn");
out.write("Agent: SSL-TESTrn");
out.write("rn");
out.flush();
BufferedReader in = new BufferedReader(
new InputStreamReader(socket.getInputStream(), "ISO-8859-1"));
String line = null;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
} finally {
socket.close();
}
}
}


  
11、httpclient的多線程處理

  使用多線程的主要目的,是為了實現(xiàn)并行的下載。在httpclient運行的過程中,每個http協(xié)議的方法,使用一個HttpConnection實例。由于連接是一種有限的資源,每個連接在某一時刻只能供一個線程和方法使用,所以需要確保在需要時正確地分配連接。HttpClient采用了一種類似jdbc連接池的方法來管理連接,這個管理工作由 MultiThreadedHttpConnectionManager完成。
MultiThreadedHttpConnectionManager connectionManager =
new MultiThreadedHttpConnectionManager();
HttpClient client = new HttpClient(connectionManager);
此是,client可以在多個線程中被用來執(zhí)行多個方法。每次調(diào)用HttpClient.executeMethod() 方法,都會去鏈接管理器申請一個連接實例,申請成功這個鏈接實例被簽出(checkout),隨之在鏈接使用完后必須歸還管理器。管理器支持兩個設(shè)置: maxConnectionsPerHost 每個主機(jī)的最大并行鏈接數(shù),默認(rèn)為2
maxTotalConnections 客戶端總并行鏈接最大數(shù),默認(rèn)為20

  管理器重新利用鏈接時,采取早歸還者先重用的方式(least recently used approach)。
  由于是使用HttpClient的程序而不是HttpClient本身來讀取應(yīng)答包的主體,所以HttpClient無法決定什么時間連接不再使用了,這也就要求在讀完應(yīng)答包的主體后必須手工顯式地調(diào)用releaseConnection()來釋放申請的鏈接。
MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
HttpClient client = new HttpClient(connectionManager);
...
// 在某個線程中。
GetMethod get = new GetMethod("http://jakarta.apache.org/");
try {
client.executeMethod(get);
// print response to stdout
System.out.println(get.getResponseBodyAsStream());
} finally {
// be sure the connection is released back to the connection
// manager
get.releaseConnection();
}
對每一個HttpClient.executeMethod須有一個method.releaseConnection()與之匹配.

12、HTTP方法


  HttpClient支持的HTTP方法有8種,下面分述之。

  1、Options

  HTTP方法Options用來向服務(wù)器發(fā)送請求,希望獲得針對由請求URL(request url)標(biāo)志的資源在請求/應(yīng)答的通信過程可以使用的功能選項。通過這個方法,客戶端可以在采取具體行動之前,就可對某一資源決定采取什么動作和/或以及一些必要條件,或者了解服務(wù)器提供的功能。這個方法最典型的應(yīng)用,就是用來獲取服務(wù)器支持哪些HTTP方法。
  HttpClient中有一個類叫OptionsMethod,來支持這個HTTP方法,利用這個類的getAllowedMethods方法,就可以很簡單地實現(xiàn)上述的典型應(yīng)用。


OptionsMethod options = new OptionsMethod("http://jakarta.apache.org");
// 執(zhí)行方法并做相應(yīng)的異常處理
...
Enumeration allowedMethods = options.getAllowedMethods();
options.releaseConnection();

  2、Get

   HTTP方法GET用來取回請求URI(request-URI)標(biāo)志的任何信息(以實體(entity)的形式),"get"這個單詞本意就是”獲取“的意思。如果請求URI指向的一個數(shù)據(jù)處理過程,那這個過程生成的數(shù)據(jù),在應(yīng)答中以實體的形式被返回,而不是將這個過程的代碼的返回。
  如果HTTP包中含有If-ModifiedSince, If-Unmodified-Since, If-Match, If-None-Match, 或 If-Range等頭字段,則GET也就變成了”條件GET“,即只有滿足上述字段描述的條件的實體才被取回,這樣可以減少一些非必需的網(wǎng)絡(luò)傳輸,或者減少為獲取某一資源的多次請求(如第一次檢查,第二次下載)。(一般的瀏覽器,都有一個臨時目錄,用來緩存一些網(wǎng)頁信息,當(dāng)再次瀏覽某個頁面的時候,只下載那些修改過的內(nèi)容,以加快瀏覽速度,就是這個道理。至于檢查,則常用比GET更好的方法HEAD來實現(xiàn)。)如果HTTP包中含有Range頭字段,那么請求URI指定的實體中,只有決定范圍條件的那部分才被取回來。(用過多線程下載工具的朋友,可能比較容易理解這一點)
  這個方法的典型應(yīng)用,用來從web服務(wù)器下載文檔。HttpClient定義了一個類叫GetMethod來支持這個方法,用GetMethod類中g(shù)etResponseBody, getResponseBodyAsStream 或 getResponseBodyAsString函數(shù)就可以取到應(yīng)答包包體中的文檔(如HTML頁面)信息。這這三個函數(shù)中,getResponseBodyAsStream通常是最好的方法,主要是因為它可以避免在處理下載的文檔之前緩存所有的下載的數(shù)據(jù)。

GetMethod get = new GetMethod("http://jakarta.apache.org");
// 執(zhí)行方法,并處理失敗的請求.
...
InputStream in = get.getResponseBodyAsStream();
// 利用輸入流來處理信息。
get.releaseConnection();

  對GetMethod的最常見的不正確的使用,是沒有將全部的應(yīng)答主體的數(shù)據(jù)讀出來。還有,必須注意要手工明確地將鏈接釋放。

  3、Head

  HTTP的Head方法,與Get方法完全一致,唯一的差別是服務(wù)器不能在應(yīng)答包中包含主體(message-body),而且一定不能包含主體。使用這個方法,可以使得客戶無需將資源下載回就可就以得到一些關(guān)于它的基本信息。這個方法常用來檢查超鏈的可訪問性以及資源最近有沒有被修改。
  HTTP的head方法最典型的應(yīng)用,是獲取資源的基本信息。HttpClient定義了HeadMethod類支持這個方法,HeadMethod類與其它*Method類一樣,用 getResponseHeaders()取回頭部信息,而沒有自己的特殊方法。

HeadMethod head = new HeadMethod("http://jakarta.apache.org");
// 執(zhí)行方法,并處理失敗的請求.
...
// 取回應(yīng)答包的頭字段信息.
Header[] headers = head.getResponseHeaders();

// 只取回最后修改日期字段的信息.
String lastModified = head.getResponseHeader("last-modified").getValue();



  4、Post

  Post在英文有“派駐”的意思,HTTP方法POST就是要求服務(wù)器接受請求包中的實體,并將其作為請求URI的下屬資源。從本質(zhì)上說,這意味著服務(wù)器要保存這個實體信息,而且通常由服務(wù)器端的程序進(jìn)行處理。Post方法的設(shè)計意圖,是要以一種統(tǒng)一的方式實現(xiàn)下列功能:
對已有的資源做評注

將信息發(fā)布到BBS、新聞組、郵件列表,或類似的文章組中

將一塊數(shù)據(jù),提交給數(shù)據(jù)處理進(jìn)程

通過追加操作,來擴(kuò)展一個數(shù)據(jù)庫
  這些都操作期待著在服務(wù)器端產(chǎn)生一定的“副作用”,如修改了數(shù)據(jù)庫等。
  HttpClient定義PostMethod類以支持該HTTP方法,在httpclient中,使用post方法有兩個基本的步驟:為請求包準(zhǔn)備數(shù)據(jù),然后讀取服務(wù)器來的應(yīng)答包的信息。通過調(diào)用 setRequestBody()函數(shù),來為請求包提供數(shù)據(jù),它可以接收三類參數(shù):輸入流、名值對數(shù)組或字符串。至于讀取應(yīng)答包需要調(diào)用 getResponseBody* 那一系列的方法,與GET方法處理應(yīng)答包的方法相同。
  常見問題是,沒有將全部應(yīng)答讀取(無論它對程序是否有用),或沒有釋放鏈接資源。



Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1488
72
Where are cookies stored? Where are cookies stored? Dec 20, 2023 pm 03:07 PM

Cookies are usually stored in the cookie folder of the browser. Cookie files in the browser are usually stored in binary or SQLite format. If you open the cookie file directly, you may see some garbled or unreadable content, so it is best to use Use the cookie management interface provided by your browser to view and manage cookies.

Where are the cookies on your computer? Where are the cookies on your computer? Dec 22, 2023 pm 03:46 PM

Cookies on your computer are stored in specific locations on your browser, depending on the browser and operating system used: 1. Google Chrome, stored in C:\Users\YourUsername\AppData\Local\Google\Chrome\User Data\Default \Cookies etc.

How cookies work How cookies work Sep 20, 2023 pm 05:57 PM

The working principle of cookies involves the server sending cookies, the browser storing cookies, and the browser processing and storing cookies. Detailed introduction: 1. The server sends a cookie, and the server sends an HTTP response header containing the cookie to the browser. This cookie contains some information, such as the user's identity authentication, preferences, or shopping cart contents. After the browser receives this cookie, it will be stored on the user's computer; 2. The browser stores cookies, etc.

What are the dangers of cookie leakage? What are the dangers of cookie leakage? Sep 20, 2023 pm 05:53 PM

The dangers of cookie leakage include theft of personal identity information, tracking of personal online behavior, and account theft. Detailed introduction: 1. Personal identity information is stolen, such as name, email address, phone number, etc. This information may be used by criminals to carry out identity theft, fraud and other illegal activities; 2. Personal online behavior is tracked and analyzed through cookies With the data in the account, criminals can learn about the user's browsing history, shopping preferences, hobbies, etc.; 3. The account is stolen, bypassing login verification, directly accessing the user's account, etc.

Where are the mobile cookies? Where are the mobile cookies? Dec 22, 2023 pm 03:40 PM

Cookies on the mobile phone are stored in the browser application of the mobile device: 1. On iOS devices, Cookies are stored in Settings -> Safari -> Advanced -> Website Data of the Safari browser; 2. On Android devices, Cookies Stored in Settings -> Site settings -> Cookies of Chrome browser, etc.

How to solve the problem that document.cookie cannot be obtained How to solve the problem that document.cookie cannot be obtained Nov 23, 2023 am 10:02 AM

Solutions for document.cookie not being obtained: 1. Browser privacy settings; 2. Same-origin policy; 3. HTTPOnly Cookie; 4. JavaScript code error; 5. Cookie does not exist or expires; 6. Cross-domain issues; 7. Viewer mode; 8. Server problems; 9. JavaScript execution timing; 10. Check console log, etc.

Send HTTP request and handle response using HttpClient in Java 11 Send HTTP request and handle response using HttpClient in Java 11 Aug 01, 2023 am 11:48 AM

Title: Sending HTTP requests and handling responses using HttpClient in Java11 Introduction: In modern Internet applications, HTTP communication with other servers is a very common task. Java provides some built-in tools that can help us achieve this goal. The latest and recommended one is the HttpClient class introduced in Java11. This article will introduce how to use HttpClient in Java11 to send HTTP requests and process responses,

Does clearing cookies have any impact? Does clearing cookies have any impact? Sep 20, 2023 pm 06:01 PM

The effects of clearing cookies include resetting personalization settings and preferences, affecting ad experience, and destroying login status and password remembering functions. Detailed introduction: 1. Reset personalized settings and preferences. If cookies are cleared, the shopping cart will be reset to empty and products need to be re-added. Clearing cookies will also cause the login status on social media platforms to be lost, requiring re-adding. Enter your username and password; 2. It affects the advertising experience. If cookies are cleared, the website will not be able to understand our interests and preferences, and will display irrelevant ads, etc.

See all articles