Httpclient4.5.*HttpClient请求,对于新建httpclient实例时保持会话
Posted wsy0202
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Httpclient4.5.*HttpClient请求,对于新建httpclient实例时保持会话相关的知识,希望对你有一定的参考价值。
package net.bill99.httpconsel; import java.io.IOException; import java.util.*; import java.util.Map.Entry; import org.apache.http.*; import org.apache.http.client.CookieStore; import org.apache.http.client.config.CookieSpecs; 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.client.protocol.HttpClientContext; import org.apache.http.config.Registry; import org.apache.http.config.RegistryBuilder; import org.apache.http.cookie.Cookie; import org.apache.http.cookie.CookieSpecProvider; import org.apache.http.impl.client.BasicCookieStore; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.cookie.BasicClientCookie; import org.apache.http.impl.cookie.BestMatchSpecFactory; import org.apache.http.impl.cookie.BrowserCompatSpecFactory; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; import java.util.HashMap; import java.util.Map; public class TestHttpClient { // 创建CookieStore实例 static CookieStore cookieStore = null; static HttpClientContext context = null; static StringBuffer cookielocal= new StringBuffer();//保存cookie String loginUrl = "http://fscposs.99bill.com/fscposs/loginProcess.htm"; String testUrl = "http://fscposs.99bill.com/fscposs/ftl/fscposs/main.jsp"; @BeforeClass public void testLogin() throws Exception { System.out.println("----testLogin"); // 直接创建client CloseableHttpClient client = HttpClients.createDefault(); HttpPost httpPost = new HttpPost(loginUrl); httpPost.setHeader("Content-Type","application/x-www-form-urlencoded"); Map parameterMap = new HashMap(); parameterMap.put("userName", "qatest_nj"); parameterMap.put("password", "99bill99"); parameterMap.put("method","login"); parameterMap.put("tokenPWD",""); UrlEncodedFormEntity postEntity = new UrlEncodedFormEntity(getParam(parameterMap), "UTF-8"); httpPost.setEntity(postEntity); System.err.println("request line:" + httpPost.getRequestLine()); try { // 执行post请求 HttpResponse httpResponse = client.execute(httpPost); String location = httpResponse.getFirstHeader("Location") .getValue(); printResponse(httpResponse); // 执行get请求 System.err.println("----the same client"); HttpGet httpGet = new HttpGet(testUrl); System.out.println("request line:" + httpGet.getRequestLine()); HttpResponse httpResponse1 = client.execute(httpGet); System.out.println("====main=====:" +EntityUtils.toString(httpResponse1.getEntity())); // cookie store,保存cookie方法 setCookieStore(httpResponse); System.err.println("cookieStore值为:"+cookieStore); // context setContext(); } catch (IOException e) { e.printStackTrace(); } finally { try { // 关闭流并释放资源 client.close(); } catch (IOException e) { e.printStackTrace(); } } } @Test public void testCookie(){ System.err.println("=======开始执行test1======:"+cookielocal); CloseableHttpClient client = HttpClients.createDefault(); HttpGet httpGet = new HttpGet(testUrl); System.err.println("cookielocal值:"+cookielocal.substring(0,cookielocal.length()-1).toString()); httpGet.setHeader("cookie",cookielocal.substring(0,cookielocal.length()-1).toString()); System.out.println("request line:" + httpGet.getRequestLine()); try { // 执行get请求 HttpResponse httpResponse = client.execute(httpGet); System.out.println("====main=====:" +EntityUtils.toString(httpResponse.getEntity())); } catch (IOException e) { e.printStackTrace(); } finally { try { // 关闭流并释放资源 client.close(); } catch (IOException e) { e.printStackTrace(); } } } public void testContext() throws Exception { System.out.println("----testContext"); // 使用context方式 CloseableHttpClient client = HttpClients.createDefault(); HttpGet httpGet = new HttpGet(testUrl); System.out.println("request line:" + httpGet.getRequestLine()); try { // 执行get请求 HttpResponse httpResponse = client.execute(httpGet, context); System.out.println("context cookies:" + context.getCookieStore().getCookies()); System.out.println("====main=====:" +EntityUtils.toString(httpResponse.getEntity())); } catch (IOException e) { e.printStackTrace(); } finally { try { // 关闭流并释放资源 client.close(); } catch (IOException e) { e.printStackTrace(); } } } public void testCookieStore() throws Exception { System.out.println("----testCookieStore"); // 使用cookieStore方式 CloseableHttpClient client = HttpClients.custom() .setDefaultCookieStore(cookieStore).build(); HttpGet httpGet = new HttpGet(testUrl); System.out.println("request line:" + httpGet.getRequestLine()); try { // 执行get请求 HttpResponse httpResponse = client.execute(httpGet); System.out.println("cookie store:" + cookieStore.getCookies()); System.out.println("====main=====:" +EntityUtils.toString(httpResponse.getEntity())); printResponse(httpResponse); } catch (IOException e) { e.printStackTrace(); } finally { try { // 关闭流并释放资源 client.close(); } catch (IOException e) { e.printStackTrace(); } } } public static void printResponse(HttpResponse httpResponse) throws Exception { // 获取响应消息实体 HttpEntity entity = httpResponse.getEntity(); // 响应状态 System.out.println("status:" + httpResponse.getStatusLine()); System.out.println("headers:"); HeaderIterator iterator = httpResponse.headerIterator(); while (iterator.hasNext()) { System.out.println(" " + iterator.next()); } // 判断响应实体是否为空 if (entity != null) { String responseString = EntityUtils.toString(entity); System.out.println("response length:" + responseString.length()); System.out.println("response content:" + responseString.replace(" ", "")); } } public static void setContext() { System.out.println("----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); } public static void setCookieStore(HttpResponse httpResponse) { System.out.println("----setCookieStore"); cookieStore = new BasicCookieStore(); Header[] headers = httpResponse.getHeaders("Set-Cookie"); for(Header header : headers) { System.out.println("----RawValue: " + header.getValue()); HeaderElement[] headerElementArray = header.getElements(); for(HeaderElement headerElement : headerElementArray) { System.out.print("Value=" + headerElement.getName()); // 获取cookie并保存 if(null != headerElement.getValue()) { cookielocal.append(headerElement.getName() + "="+ headerElement.getValue()+";"); System.out.println(" key=" + headerElement.getValue()); } BasicClientCookie cookie = new BasicClientCookie(headerElement.getName(),headerElement.getValue()); cookie.setVersion(0); NameValuePair[] nameValuePairArray = headerElement.getParameters(); for(NameValuePair nameValuePair : nameValuePairArray) { System.out.println("Parameter: " + nameValuePair.getName() + " <-|-> " + nameValuePair.getValue()); switch (nameValuePair.getName()){ case "Domain" : if(nameValuePair.getValue()!=null) { cookie.setDomain(nameValuePair.getValue()); } break; case "Path": if(nameValuePair.getValue()!=null) { cookie.setDomain(nameValuePair.getValue()); } break; default: break; } } cookieStore.addCookie(cookie); } } } 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; } }
以上是关于Httpclient4.5.*HttpClient请求,对于新建httpclient实例时保持会话的主要内容,如果未能解决你的问题,请参考以下文章