HttpClient---cookie(保持登录)

public class APIMthod {
    // 创建CookieStore实例
    private static CookieStore cookieStore = null;
    private static HttpClientContext context = null;
    private static String response = "";

    public static String sendGetByHttpCient(String url){

        HttpResponse httpResponse = null;
        CloseableHttpClient client = HttpClients.custom().setDefaultCookieStore(cookieStore).build();

        try {
            HttpGet httpGet = new HttpGet(url);
            httpResponse = client.execute(httpGet);
            response = printResponse(httpResponse);
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                // 关闭流并释放资源
                client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return response;
    }

    public static String sendPostByHttpCient(String url, Map parameterMap){
        HttpResponse httpResponse = null;
        UrlEncodedFormEntity postEntity = null;
        CloseableHttpClient client = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
        try {
            HttpPost httpPost = new HttpPost(url);
            postEntity = new UrlEncodedFormEntity(getParam(parameterMap), "UTF-8");
            httpPost.setEntity(postEntity);

            httpResponse = client.execute(httpPost);
            response = printResponse(httpResponse);
            if (cookieStore == null || "".equals(cookieStore)) {
                String host = httpPost.getURI().getHost();
                setCookieStore(httpResponse, host);
            }

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                // 关闭流并释放资源
                client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return response;
    }

    public static String printResponse(HttpResponse httpResponse) throws ParseException, IOException {
        String responseString = "";
        // 获取响应消息实体
        HttpEntity entity = httpResponse.getEntity();
        // 判断响应实体是否为空
        if (entity != null) {
            responseString = EntityUtils.toString(entity);
        }
        return responseString;
    }

    public static void setContext() {
        context = HttpClientContext.create();
        Registry registry = RegistryBuilder
                . 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,String host) {
        cookieStore = new BasicCookieStore();
        // JSESSIONID
        if (null == httpResponse.getFirstHeader("Set-Cookie")) {
            cookieStore = null;
        }else {
            String setCookie = httpResponse.getFirstHeader("Set-Cookie").getValue();
            String JSESSIONID = setCookie.substring("JSESSIONID=".length(),setCookie.indexOf(";"));
            // 新建一个Cookie
            BasicClientCookie cookie = new BasicClientCookie("JSESSIONID",JSESSIONID);
            cookie.setVersion(0);
            cookie.setDomain(host);
            cookie.setPath("/");
            cookieStore.addCookie(cookie);
        }
    }

    public static List getCookies(){
        if (null == cookieStore) {
            return null;
        }
        return cookieStore.getCookies();
    }

    public static void deleteCookies(){
        if (cookieStore != null) {
            cookieStore.clear();
            cookieStore = null;
        }
    }

    public static List getParam(Map parameterMap) {
        List param = new ArrayList();
        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;
    }

你可能感兴趣的:(自动化测试)