COOKIE保持回話
httpclient4.x自帶維護回話的功能,只要使用同一個httpclient且未關閉鏈接,就能夠使用相同的回話來訪問其餘要求登錄驗證的服務。
若是須要使用HttpClient池,而且想要作到一次登錄的會話供多個httpClient鏈接使用,就須要本身保存回話信息。
客戶端的回話信息是保存在cookie中的(JESSIONID),因此只須要將登錄成功返回的cookie複製到各個HttpClient使用便可。
使用Cookie的方法有兩種,能夠本身使用CookieStore來保存,也能夠經過HttpClientContext上下文來維持
使用cookie的兩種方法
*) 使用CookieStore來保存
*) 經過HttpClientContext上下文來維持
使用cookie測試登錄
public void testLogin(){
//間接建立HttpClient
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
ColseableHttpClient client = httpClientBuilder.build();
//直接建立client
CloseableHttpClient client = HttpClients.createDefault();
//--------------------------------------------------------------------------------
HttpPost httpPost = new HttpPost(loginUrl);
Map parameterMap = new HashMap();
paramterMap.put("username","admin");
paramterMap.put("password","admin123");
--------------------------------------------------------------------------------
UrlEncodedFormEntity postEntity = new UrlEncodedFormEntity(getParam(paramterMap),"utf-8");
httpPost.setEntity(postEntity);
try{
//--執行post請求
HttpResponse httpResponse = client.execute(httpPost);
String location = httpResponse.getFirstHeader("Location").getValue();
printResponse(httpResponse);
//--執行get請求
HttpGet httpGet = new HttpGet(testUrl);
HttpResponse response1 = client.execute(httpGet);
printResponse(httpResponse);
--------------------------------------------------------------------------------
//cookie Store
setCookieStore(httpResponse);
//context 注意順序
setContext();
}catch(Exception e){
e.printStackTrace();
}
}
--------------------------------------------------------------------------------
public static List<NameValuePair> getParam(Map parameterMap) {
List<NameValuePair> param = new ArrayList<NameValuePair>();
Iterator it = parameterMap.entrySet().iterator();
while (it.hasNext()) {
Entry parmEntry = (Entry) it.next();
param.add(new BasicNameValuePair((String) parmEntry.getKey(),
(String) parmEntry.getValue()));
}
return param;
}
-------------------------------------------------------------------------
public static void printResponse(HttpResponse httpResponse)
throws ParseException, IOException {
// 獲取響應消息實體
HttpEntity entity = httpResponse.getEntity();
// 響應狀態
System.out.println("status:" + httpResponse.getStatusLine());
System.out.println("headers:");
HeaderIterator iterator = httpResponse.headerIterator();
while (iterator.hasNext()) {
System.out.println("\t" + iterator.next());
}
// 判斷響應實體是否爲空
if (entity != null) {
String responseString = EntityUtils.toString(entity);
System.out.println("response length:" + responseString.length());
System.out.println("response content:"
+ responseString.replace("\r\n", ""));
}
}
經過CookieStore保持上下文的回話
static CookieStore cookieStore = null;
public void testCookieStore() throws Exception{
//使用cookieStore方式
cookieStore= setCookieStore();
CloseableHttpClient client = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
HttpGet httpGet = new HttpGet(testUrl);
//執行get請求
try{
HttpResponse response = client.execute(httpGet);
printResponse(response);
}catch(Exception e){
e.printStackTrace();
}
}
public static void setCookieStore(HttpResponse response){
cookieStore = new BasicCookieStore();
//JSSIONID
String setCookie - httpResponse.getFirestHeader("Set-Cookie").getValue();
String JESSIONID = setCookie.substring("JESSIONID=".length(),setCookie.indexOf(";"));
//新建一個COOKIE
BasicClientCookie cookie = new BasicClientCookie("JESSIONID",JESSIONID);
cookie.setVersion(0);
cookie.setDomain("127.0.0.1");
cookie.setPath("/path");
// cookie.setAttribute(ClientCookie.VERSION_ATTR, "0");
// cookie.setAttribute(ClientCookie.DOMAIN_ATTR, "127.0.0.1");
// cookie.setAttribute(ClientCookie.PORT_ATTR, "8080");
// cookie.setAttribute(ClientCookie.PATH_ATTR, "/CwlProWeb");
cookieStore.addCookie(cookie);
}
使用context上下文保持回話
static HttpClientContext context = null;
public void testContext() throws Exception(
//使用context方式
CloseableHttpClient client = HttpClients.createDefault():
HttpGet httpGet = new HttpGet(testUrl);
try{
//執行get請求
HttpResponse httpResponse = client.execute(httpGet,context);
printResponse(httpResponse);
}catch(Exception e){
e.printStackTrace();
}finally{
//關閉流並釋放資源
client.close();
}
)
public static void setContext() {
context = HttpClientContext.create();
Registry<CookieSpecProvider> registry = RegistryBuilder
.<CookieSpecProvider> create()
.register(CookieSpecs.BEST_MATCH, new BestMatchSpecFactory())
.register(CookieSpecs.BROWSER_COMPATIBILITY, new BrowserCompatSpecFactory()).build();
context.setCookieSpecRegistry(registry);
context.setCookieStore(cookieStore);
}