Example usage for org.apache.http.cookie Cookie toString

List of usage examples for org.apache.http.cookie Cookie toString

Introduction

In this page you can find the example usage for org.apache.http.cookie Cookie toString.

Prototype

public String toString() 

Source Link

Document

Returns a string representation of the object.

Usage

From source file:com.bright.json.JSonRequestor.java

public static String doRequest(String jsonReq, String myURL, List<Cookie> cookies) {
    try {//from   w  ww. ja  v a  2s .c  om

        /* HttpClient httpclient = new DefaultHttpClient(); */

        HttpClient httpclient = getNewHttpClient();
        CookieStore cookieStore = new BasicCookieStore();
        Cookie[] cookiearray = cookies.toArray(new Cookie[0]);
        cookieStore.addCookie(cookiearray[0]);
        HttpContext localContext = new BasicHttpContext();
        localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);

        /* httpclient = WebClientDevWrapper.wrapClient(httpclient); */

        httpclient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);
        HttpParams params = httpclient.getParams();
        HttpConnectionParams.setConnectionTimeout(params, 1000);
        HttpConnectionParams.setSoTimeout(params, 1000);
        HttpPost httppost = new HttpPost(myURL);
        StringEntity stringEntity = new StringEntity(jsonReq);
        stringEntity.setContentType("application/json");
        httppost.setEntity(stringEntity);

        System.out.println("executing request " + httppost.getRequestLine()
                + System.getProperty("line.separator") + jsonReq);

        HttpResponse response = httpclient.execute(httppost, localContext);

        System.out.println(response + "\n");
        for (Cookie c : ((AbstractHttpClient) httpclient).getCookieStore().getCookies()) {
            System.out.println("\n Cookie: " + c.toString() + "\n");
        }

        HttpEntity resEntity = response.getEntity();

        System.out.println("----------------------------------------");
        System.out.println(response.getStatusLine());
        if (resEntity != null) {
            System.out.println("Response content length: " + resEntity.getContentLength());
            System.out.println("Chunked?: " + resEntity.isChunked());
            String message = new String(EntityUtils.toString(resEntity));
            System.out.println(message);
            return message;
        }
        EntityUtils.consume(resEntity);

    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }

    return null;

}

From source file:com.bright.json.JSonRequestor.java

public static List<Cookie> doLogin(String user, String pass, String myURL) {
    try {//w w  w.  ja  v a 2 s  .com
        cmLogin loginReq = new cmLogin("login", user, pass);

        GsonBuilder builder = new GsonBuilder();

        Gson g = builder.create();
        String json = g.toJson(loginReq);

        /* HttpClient httpclient = new DefaultHttpClient(); */

        HttpClient httpclient = getNewHttpClient();
        CookieStore cookieStore = new BasicCookieStore();

        HttpContext localContext = new BasicHttpContext();
        localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);

        /* httpclient = WebClientDevWrapper.wrapClient(httpclient); */

        httpclient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);
        HttpParams params = httpclient.getParams();
        HttpConnectionParams.setConnectionTimeout(params, 1000);
        HttpConnectionParams.setSoTimeout(params, 1000);
        HttpPost httppost = new HttpPost(myURL);
        StringEntity stringEntity = new StringEntity(json);
        stringEntity.setContentType("application/json");
        httppost.setEntity(stringEntity);

        System.out.println("executing request " + httppost.getRequestLine());
        HttpResponse response = httpclient.execute(httppost, localContext);

        System.out.println(response + "\n");
        for (Cookie c : ((AbstractHttpClient) httpclient).getCookieStore().getCookies()) {
            System.out.println("\n Cookie: " + c.toString() + "\n");
        }

        List<Cookie> cookies = cookieStore.getCookies();
        for (int i = 0; i < cookies.size(); i++) {
            System.out.println("Local cookie: " + cookies.get(i));
        }

        HttpEntity resEntity = response.getEntity();

        System.out.println("----------------------------------------");
        System.out.println(response.getStatusLine());
        if (resEntity != null) {
            System.out.println("Response content length: " + resEntity.getContentLength());
            System.out.println("Chunked?: " + resEntity.isChunked());
            String message = new String(EntityUtils.toString(resEntity));
            System.out.println(message);
            return cookies;
        }
        EntityUtils.consume(resEntity);

    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }

    return null;

}

From source file:nya.miku.wishmaster.http.cloudflare.CloudflareChecker.java

static void removeCookie(CookieStore store, String name) {
    boolean flag = false;
    for (Cookie cookie : store.getCookies()) {
        if (cookie.getName().equals(name)) {
            if (cookie instanceof SetCookie) {
                flag = true;//from  w  ww.j  a v a2 s  . c o m
                ((SetCookie) cookie).setExpiryDate(new Date(0));
            } else {
                Logger.e(TAG,
                        "cannot remove cookie (object does not implement SetCookie): " + cookie.toString());
            }
        }
    }
    if (flag)
        store.clearExpired(new Date());
}

From source file:zz.pseas.ghost.client.GhostClient.java

public void showCookies() {
    List<Cookie> cookies = context.getCookieStore().getCookies();
    for (Cookie c : cookies) {
        System.out.println(c.toString());
    }/*from   w w w  .  j  a va  2  s  .com*/
}

From source file:edu.usu.sdl.apiclient.AbstractService.java

protected void logon() {
    //get the initial cookies
    HttpGet httpget = new HttpGet(loginModel.getServerUrl());
    try (CloseableHttpResponse response = httpclient.execute(httpget)) {
        HttpEntity entity = response.getEntity();

        log.log(Level.FINE, "Login form get: {0}", response.getStatusLine());
        EntityUtils.consume(entity);//  w ww .j a  v  a  2s . c o  m

        log.log(Level.FINEST, "Initial set of cookies:");
        List<Cookie> cookies = cookieStore.getCookies();
        if (cookies.isEmpty()) {
            log.log(Level.FINEST, "None");
        } else {
            for (Cookie cookie : cookies) {
                log.log(Level.FINEST, "- {0}", cookie.toString());
            }
        }
    } catch (IOException ex) {
        throw new ConnectionException("Unable to Connect.", ex);
    }

    //login
    try {
        HttpUriRequest login = RequestBuilder.post().setUri(new URI(loginModel.getSecurityUrl()))
                .addParameter(loginModel.getUsernameField(), loginModel.getUsername())
                .addParameter(loginModel.getPasswordField(), loginModel.getPassword()).build();
        try (CloseableHttpResponse response = httpclient.execute(login)) {
            HttpEntity entity = response.getEntity();

            log.log(Level.FINE, "Login form get: {0}", response.getStatusLine());
            EntityUtils.consume(entity);

            log.log(Level.FINEST, "Post logon cookies:");
            List<Cookie> cookies = cookieStore.getCookies();
            if (cookies.isEmpty()) {
                log.log(Level.FINEST, "None");
            } else {
                for (Cookie cookie : cookies) {
                    log.log(Level.FINEST, "- {0}", cookie.toString());
                }
            }
        }

        //For some reason production requires getting the first page first
        RequestConfig defaultRequestConfig = RequestConfig.custom().setCircularRedirectsAllowed(true).build();

        HttpUriRequest data = RequestBuilder.get().setUri(new URI(loginModel.getServerUrl()))
                .addHeader(CONTENT_TYPE, MEDIA_TYPE_JSON).setConfig(defaultRequestConfig).build();

        try (CloseableHttpResponse response = httpclient.execute(data)) {
            log.log(Level.FINE, "Response Status from connection: {0}  {1}", new Object[] {
                    response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase() });
            HttpEntity entity1 = response.getEntity();
            EntityUtils.consume(entity1);
        }

    } catch (IOException | URISyntaxException ex) {
        throw new ConnectionException("Unable to login.", ex);
    }
}

From source file:org.archive.modules.fetcher.BdbCookieStoreTest.java

protected void assertCookieListsEquivalent(Collection<Cookie> list1, Collection<Cookie> list2) {
    Comparator<Cookie> comparator = new Comparator<Cookie>() {
        @Override/*from   w  w w  .j a va 2s . com*/
        public int compare(Cookie o1, Cookie o2) {
            return o1.toString().compareTo(o2.toString());
        }
    };

    ArrayList<Cookie> sorted1 = new ArrayList<Cookie>(list1);
    Collections.sort(sorted1, comparator);
    ArrayList<Cookie> sorted2 = new ArrayList<Cookie>(list2);
    Collections.sort(sorted2, comparator);

    assertEquals(list1.size(), list2.size());
    assertEquals(sorted1.size(), sorted2.size());

    Iterator<Cookie> iter1 = sorted1.iterator();
    Iterator<Cookie> iter2 = sorted2.iterator();
    for (int i = 0; i < list1.size(); i++) {
        Cookie c1 = iter1.next();
        Cookie c2 = iter2.next();
        assertCookiesIdentical(c1, c2);
    }
}

From source file:com.mockey.model.RequestFromClient.java

public String getCookieInfoAsString() {
    StringBuffer buf = new StringBuffer();

    for (Cookie cookie : this.httpClientCookies) {

        buf.append(cookie.toString() + "\n\n");
    }/*from   www.j a v  a 2 s. com*/

    return buf.toString();
}

From source file:com.mockey.ClientExecuteProxy.java

/**
 * // w  ww.  j  a v  a 2s  .  c o m
 * @param twistInfo
 * @param proxyServer
 * @param realServiceUrl
 * @param httpMethod
 * @param request
 * @return
 * @throws ClientExecuteProxyException
 */
public ResponseFromService execute(TwistInfo twistInfo, ProxyServerModel proxyServer, Url realServiceUrl,
        boolean allowRedirectFollow, RequestFromClient request) throws ClientExecuteProxyException {
    log.info("Request: " + String.valueOf(realServiceUrl));

    // general setup
    SchemeRegistry supportedSchemes = new SchemeRegistry();

    // Register the "http" and "https" protocol schemes, they are
    // required by the default operator to look up socket factories.
    supportedSchemes.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
    supportedSchemes.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory()));

    // prepare parameters
    HttpParams params = new BasicHttpParams();
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, HTTP.ISO_8859_1);
    HttpProtocolParams.setUseExpectContinue(params, false);

    ClientConnectionManager ccm = new ThreadSafeClientConnManager(supportedSchemes);
    DefaultHttpClient httpclient = new DefaultHttpClient(ccm, params);

    if (!allowRedirectFollow) {
        // Do NOT allow for 302 REDIRECT
        httpclient.setRedirectStrategy(new DefaultRedirectStrategy() {
            public boolean isRedirected(HttpRequest request, HttpResponse response, HttpContext context) {
                boolean isRedirect = false;
                try {
                    isRedirect = super.isRedirected(request, response, context);
                } catch (ProtocolException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                if (!isRedirect) {
                    int responseCode = response.getStatusLine().getStatusCode();
                    if (responseCode == 301 || responseCode == 302) {
                        return true;
                    }
                }
                return isRedirect;
            }
        });
    } else {
        // Yes, allow for 302 REDIRECT
        // Nothing needed here.
    }

    // Prevent CACHE, 304 not modified
    //      httpclient.addRequestInterceptor(new HttpRequestInterceptor() {
    //         public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {
    //            
    //            request.setHeader("If-modified-Since", "Fri, 13 May 2006 23:54:18 GMT");
    //
    //         }
    //      });

    CookieStore cookieStore = httpclient.getCookieStore();
    for (Cookie httpClientCookie : request.getHttpClientCookies()) {
        // HACK:
        // httpClientCookie.getValue();
        cookieStore.addCookie(httpClientCookie);
    }
    // httpclient.setCookieStore(cookieStore);

    if (ClientExecuteProxy.cookieStore == null) {
        ClientExecuteProxy.cookieStore = httpclient.getCookieStore();

    } else {
        httpclient.setCookieStore(ClientExecuteProxy.cookieStore);
    }

    StringBuffer requestCookieInfo = new StringBuffer();
    // Show what cookies are in the store .
    for (Cookie cookie : ClientExecuteProxy.cookieStore.getCookies()) {
        log.debug("Cookie in the cookie STORE: " + cookie.toString());
        requestCookieInfo.append(cookie.toString() + "\n\n\n");

    }

    if (proxyServer.isProxyEnabled()) {
        // make sure to use a proxy that supports CONNECT
        httpclient.getCredentialsProvider().setCredentials(proxyServer.getAuthScope(),
                proxyServer.getCredentials());
        httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxyServer.getHttpHost());
    }

    // TWISTING
    Url originalRequestUrlBeforeTwisting = null;
    if (twistInfo != null) {
        String fullurl = realServiceUrl.getFullUrl();
        String twistedUrl = twistInfo.getTwistedValue(fullurl);
        if (twistedUrl != null) {
            originalRequestUrlBeforeTwisting = realServiceUrl;
            realServiceUrl = new Url(twistedUrl);
        }
    }

    ResponseFromService responseMessage = null;
    try {
        HttpHost htttphost = new HttpHost(realServiceUrl.getHost(), realServiceUrl.getPort(),
                realServiceUrl.getScheme());

        HttpResponse response = httpclient.execute(htttphost, request.postToRealServer(realServiceUrl));
        if (response.getStatusLine().getStatusCode() == 302) {
            log.debug("FYI: 302 redirect occuring from " + realServiceUrl.getFullUrl());
        }
        responseMessage = new ResponseFromService(response);
        responseMessage.setOriginalRequestUrlBeforeTwisting(originalRequestUrlBeforeTwisting);
        responseMessage.setRequestUrl(realServiceUrl);
    } catch (Exception e) {
        log.error(e);
        throw new ClientExecuteProxyException("Unable to retrieve a response. ", realServiceUrl, e);
    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();
    }

    // Parse out the response information we're looking for
    // StringBuffer responseCookieInfo = new StringBuffer();
    // // Show what cookies are in the store .
    // for (Cookie cookie : ClientExecuteProxy.cookieStore.getCookies()) {
    // log.info("Cookie in the cookie STORE: " + cookie.toString());
    // responseCookieInfo.append(cookie.toString() + "\n\n\n");
    //
    // }
    // responseMessage.setRequestCookies(requestCookieInfo.toString());
    // responseMessage.setResponseCookies(responseCookieInfo.toString());
    return responseMessage;
}

From source file:org.archive.modules.fetcher.CookieStoreTest.java

protected void assertCookieListsEquivalent(List<Cookie> list1, List<Cookie> list2) {
    Comparator<Cookie> comparator = new Comparator<Cookie>() {
        @Override/*  w w  w.  jav  a 2  s.  co  m*/
        public int compare(Cookie o1, Cookie o2) {
            return o1.toString().compareTo(o2.toString());
        }
    };

    ArrayList<Cookie> sorted1 = new ArrayList<Cookie>(list1);
    Collections.sort(sorted1, comparator);
    ArrayList<Cookie> sorted2 = new ArrayList<Cookie>(list2);
    Collections.sort(sorted2, comparator);

    assertEquals(list1.size(), list2.size());
    assertEquals(sorted1.size(), sorted2.size());

    Iterator<Cookie> iter1 = sorted1.iterator();
    Iterator<Cookie> iter2 = sorted2.iterator();
    for (int i = 0; i < sorted1.size(); i++) {
        Cookie c1 = iter1.next();
        Cookie c2 = iter2.next();
        assertCookiesIdentical(c1, c2);
    }
}

From source file:com.intuit.tank.httpclient4.TankHttpClient4.java

private void sendRequest(BaseRequest request, @Nonnull HttpRequestBase method, String requestBody) {
    String uri = null;//from  w  w  w . j a v a2 s  .  c  o  m
    long waitTime = 0L;
    CloseableHttpResponse response = null;
    try {
        uri = method.getURI().toString();
        LOG.debug(request.getLogUtil().getLogMessage(
                "About to " + method.getMethod() + " request to " + uri + " with requestBody  " + requestBody,
                LogEventType.Informational));
        List<String> cookies = new ArrayList<String>();
        if (context.getCookieStore().getCookies() != null) {
            for (Cookie cookie : context.getCookieStore().getCookies()) {
                cookies.add("REQUEST COOKIE: " + cookie.toString());
            }
        }
        request.logRequest(uri, requestBody, method.getMethod(), request.getHeaderInformation(), cookies,
                false);
        setHeaders(request, method, request.getHeaderInformation());
        long startTime = System.currentTimeMillis();
        request.setTimestamp(new Date(startTime));
        response = httpclient.execute(method, context);

        // read response body
        byte[] responseBody = new byte[0];
        // check for no content headers
        if (response.getStatusLine().getStatusCode() != 203 && response.getStatusLine().getStatusCode() != 202
                && response.getStatusLine().getStatusCode() != 204) {
            try {
                InputStream httpInputStream = response.getEntity().getContent();
                responseBody = IOUtils.toByteArray(httpInputStream);
            } catch (Exception e) {
                LOG.warn("could not get response body: " + e);
            }
        }
        long endTime = System.currentTimeMillis();
        processResponse(responseBody, startTime, endTime, request, response.getStatusLine().getReasonPhrase(),
                response.getStatusLine().getStatusCode(), response.getAllHeaders());
        waitTime = endTime - startTime;
    } catch (Exception ex) {
        LOG.error(request.getLogUtil().getLogMessage(
                "Could not do " + method.getMethod() + " to url " + uri + " |  error: " + ex.toString(),
                LogEventType.IO), ex);
        throw new RuntimeException(ex);
    } finally {
        try {
            method.releaseConnection();
            if (response != null) {
                response.close();
            }
        } catch (Exception e) {
            LOG.warn("Could not release connection: " + e, e);
        }
        if (method.getMethod().equalsIgnoreCase("post")
                && request.getLogUtil().getAgentConfig().getLogPostResponse()) {
            LOG.info(request.getLogUtil()
                    .getLogMessage("Response from POST to " + request.getRequestUrl() + " got status code "
                            + request.getResponse().getHttpCode() + " BODY { " + request.getResponse().getBody()
                            + " }", LogEventType.Informational));
        }
    }
    if (waitTime != 0) {
        doWaitDueToLongResponse(request, waitTime, uri);
    }
}