Search in sources :

Example 31 with BasicClientCookie

use of org.apache.http.impl.cookie.BasicClientCookie in project nanohttpd by NanoHttpd.

the class CookieIntegrationTest method testServerReceivesMultipleCookiesSentFromClient.

@Test
public void testServerReceivesMultipleCookiesSentFromClient() throws Exception {
    Calendar calendar = Calendar.getInstance();
    calendar.add(Calendar.DAY_OF_YEAR, 100);
    Date date = calendar.getTime();
    BasicClientCookie clientCookie0 = new BasicClientCookie("name0", "value0");
    BasicClientCookie clientCookie1 = new BasicClientCookie("name1", "value1");
    BasicClientCookie clientCookie2 = new BasicClientCookie("name2", "value2");
    BasicClientCookie clientCookie3 = new BasicClientCookie("name3", "value3");
    clientCookie0.setExpiryDate(date);
    clientCookie0.setDomain("localhost");
    clientCookie1.setExpiryDate(date);
    clientCookie1.setDomain("localhost");
    clientCookie2.setExpiryDate(date);
    clientCookie2.setDomain("localhost");
    clientCookie3.setExpiryDate(date);
    clientCookie3.setDomain("localhost");
    this.httpclient.getCookieStore().addCookie(clientCookie0);
    this.httpclient.getCookieStore().addCookie(clientCookie1);
    this.httpclient.getCookieStore().addCookie(clientCookie2);
    this.httpclient.getCookieStore().addCookie(clientCookie3);
    HttpGet httpget = new HttpGet("http://localhost:8192/");
    ResponseHandler<String> responseHandler = new BasicResponseHandler();
    this.httpclient.execute(httpget, responseHandler);
    assertEquals(4, this.testServer.cookiesReceived.size());
}
Also used : Calendar(java.util.Calendar) HttpGet(org.apache.http.client.methods.HttpGet) BasicResponseHandler(org.apache.http.impl.client.BasicResponseHandler) BasicClientCookie(org.apache.http.impl.cookie.BasicClientCookie) Date(java.util.Date) Test(org.junit.Test)

Example 32 with BasicClientCookie

use of org.apache.http.impl.cookie.BasicClientCookie in project new-cloud by xie-summer.

the class HttpUtils method executeHttpRequestWithCookie.

private static HttpResult executeHttpRequestWithCookie(HttpUriRequest request, Map<String, String> reqHeader, int timeoutMills, String charset, List<BasicClientCookie> cookies) {
    hostCount(request);
    CookieStore cookieStore = getCookieStore(cookies);
    CloseableHttpClient client = getHttpClient(CONNECTION_TIMEOUT, timeoutMills, cookieStore);
    if (reqHeader != null) {
        for (String name : reqHeader.keySet()) {
            request.addHeader(name, reqHeader.get(name));
        }
    }
    try {
        List<Cookie> reqcookie = cookieStore.getCookies();
        CloseableHttpResponse response = client.execute(request);
        try {
            HttpEntity entiry = getEntity(response);
            String result = "";
            if (entiry != null) {
                result = EntityUtils.toString(getEntity(response), charset);
            }
            if (isSuccess(response)) {
                HttpResult ret = HttpResult.getSuccessReturn(result);
                addHeader(ret, response);
                List<Cookie> cookieList = cookieStore.getCookies();
                addCookie(ret, cookieList, reqcookie);
                return ret;
            } else {
                int statusCode = response.getStatusLine().getStatusCode();
                HttpResult ret = HttpResult.getFailure("httpStatus:" + response.getStatusLine().getStatusCode(), statusCode, result);
                addHeader(ret, response);
                String msg = "httpStatus:" + statusCode + response.getStatusLine().getReasonPhrase() + ", Header: " + ret.getAllHeaders();
                DB_LOGGER.error("ERROR HttpUtils:" + msg + request.getURI());
                request.abort();
                return ret;
            }
        } finally {
            response.close();
        }
    } catch (HttpHostConnectException e) {
        request.abort();
        DB_LOGGER.error(request.getURI() + ":" + LoggerUtils.getExceptionTrace(e, 30));
        return HttpResult.getFailure(request.getURI() + " exception:" + e.getClass().getCanonicalName(), HTTP_STATUSCODE_HTTP_HOST_CONNECT_EXCEPTION);
    } catch (ConnectTimeoutException e) {
        request.abort();
        DB_LOGGER.error(request.getURI() + ":" + LoggerUtils.getExceptionTrace(e, 30));
        return HttpResult.getFailure(request.getURI() + " exception:" + e.getClass().getCanonicalName(), HTTP_STATUSCODE_CONNECT_TIMEOUT_EXCEPTION);
    } catch (SocketTimeoutException e) {
        request.abort();
        DB_LOGGER.error(request.getURI() + ":" + LoggerUtils.getExceptionTrace(e, 30));
        return HttpResult.getFailure(request.getURI() + " exception:" + e.getClass().getCanonicalName(), HTTP_STATUSCODE_SOCKET_TIMEOUT_EXCEPTION);
    } catch (Exception e) {
        request.abort();
        DB_LOGGER.error(request.getURI() + ":" + LoggerUtils.getExceptionTrace(e, 30));
        return HttpResult.getFailure(request.getURI() + " exception:" + e.getClass().getCanonicalName(), EXCEPTION_HTTP_STATUSCODE);
    }
}
Also used : Cookie(org.apache.http.cookie.Cookie) BasicClientCookie(org.apache.http.impl.cookie.BasicClientCookie) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) HttpHostConnectException(org.apache.http.conn.HttpHostConnectException) KeyManagementException(java.security.KeyManagementException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) ConnectTimeoutException(org.apache.http.conn.ConnectTimeoutException) SocketTimeoutException(java.net.SocketTimeoutException) CookieStore(org.apache.http.client.CookieStore) BasicCookieStore(org.apache.http.impl.client.BasicCookieStore) SocketTimeoutException(java.net.SocketTimeoutException) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) HttpHostConnectException(org.apache.http.conn.HttpHostConnectException) ConnectTimeoutException(org.apache.http.conn.ConnectTimeoutException)

Example 33 with BasicClientCookie

use of org.apache.http.impl.cookie.BasicClientCookie in project webmagic by code4craft.

the class HttpUriRequestConverter method convertHttpClientContext.

private HttpClientContext convertHttpClientContext(Request request, Site site, Proxy proxy) {
    HttpClientContext httpContext = new HttpClientContext();
    if (proxy != null && proxy.getUsername() != null) {
        AuthState authState = new AuthState();
        authState.update(new BasicScheme(ChallengeState.PROXY), new UsernamePasswordCredentials(proxy.getUsername(), proxy.getPassword()));
        httpContext.setAttribute(HttpClientContext.PROXY_AUTH_STATE, authState);
    }
    if (request.getCookies() != null && !request.getCookies().isEmpty()) {
        CookieStore cookieStore = new BasicCookieStore();
        for (Map.Entry<String, String> cookieEntry : request.getCookies().entrySet()) {
            BasicClientCookie cookie1 = new BasicClientCookie(cookieEntry.getKey(), cookieEntry.getValue());
            cookie1.setDomain(UrlUtils.removePort(UrlUtils.getDomain(request.getUrl())));
            cookieStore.addCookie(cookie1);
        }
        httpContext.setCookieStore(cookieStore);
    }
    return httpContext;
}
Also used : BasicScheme(org.apache.http.impl.auth.BasicScheme) CookieStore(org.apache.http.client.CookieStore) BasicCookieStore(org.apache.http.impl.client.BasicCookieStore) BasicCookieStore(org.apache.http.impl.client.BasicCookieStore) AuthState(org.apache.http.auth.AuthState) HttpClientContext(org.apache.http.client.protocol.HttpClientContext) BasicClientCookie(org.apache.http.impl.cookie.BasicClientCookie) Map(java.util.Map) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials)

Example 34 with BasicClientCookie

use of org.apache.http.impl.cookie.BasicClientCookie in project zm-mailbox by Zimbra.

the class UserServlet method doHttpOp.

private static Pair<Header[], HttpResponse> doHttpOp(ZAuthToken authToken, HttpRequestBase method) throws ServiceException {
    // create an HTTP client with the same cookies
    String url = "";
    String hostname = "";
    url = method.getURI().toString();
    hostname = method.getURI().getHost();
    HttpClientBuilder clientBuilder = ZimbraHttpConnectionManager.getInternalHttpConnMgr().newHttpClient();
    Map<String, String> cookieMap = authToken.cookieMap(false);
    if (cookieMap != null) {
        BasicCookieStore cookieStore = new BasicCookieStore();
        for (Map.Entry<String, String> ck : cookieMap.entrySet()) {
            BasicClientCookie cookie = new BasicClientCookie(ck.getKey(), ck.getValue());
            cookie.setDomain(hostname);
            cookie.setPath("/");
            cookie.setSecure(false);
            cookieStore.addCookie(cookie);
        }
        clientBuilder.setDefaultCookieStore(cookieStore);
        RequestConfig reqConfig = RequestConfig.copy(ZimbraHttpConnectionManager.getInternalHttpConnMgr().getZimbraConnMgrParams().getReqConfig()).setCookieSpec(CookieSpecs.BROWSER_COMPATIBILITY).build();
        clientBuilder.setDefaultRequestConfig(reqConfig);
        if (method.getMethod().equalsIgnoreCase("PUT")) {
            clientBuilder.setRetryHandler(new InputStreamRequestHttpRetryHandler());
        }
    }
    if (method instanceof HttpPut) {
        long contentLength = ((HttpPut) method).getEntity().getContentLength();
        if (contentLength > 0) {
            // 100kbps in millis
            int timeEstimate = Math.max(10000, (int) (contentLength / 100));
            // cannot set connection time using our ZimbrahttpConnectionManager,
            // see comments in ZimbrahttpConnectionManager.
            // actually, length of the content to Put should not be a factor for
            // establishing a connection, only read time out matter, which we set
            // client.getHttpConnectionManager().getParams().setConnectionTimeout(timeEstimate);
            SocketConfig config = SocketConfig.custom().setSoTimeout(timeEstimate).build();
            clientBuilder.setDefaultSocketConfig(config);
        }
    }
    HttpClient client = clientBuilder.build();
    try {
        HttpResponse response = HttpClientUtil.executeMethod(client, method);
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode == HttpStatus.SC_NOT_FOUND || statusCode == HttpStatus.SC_FORBIDDEN)
            throw MailServiceException.NO_SUCH_ITEM(-1);
        else if (statusCode != HttpStatus.SC_OK && statusCode != HttpStatus.SC_CREATED && statusCode != HttpStatus.SC_NO_CONTENT)
            throw ServiceException.RESOURCE_UNREACHABLE(response.getStatusLine().getReasonPhrase(), null, new ServiceException.InternalArgument(HTTP_URL, url, ServiceException.Argument.Type.STR), new ServiceException.InternalArgument(HTTP_STATUS_CODE, statusCode, ServiceException.Argument.Type.NUM));
        List<Header> headers = new ArrayList<Header>(Arrays.asList(response.getAllHeaders()));
        headers.add(new BasicHeader("X-Zimbra-Http-Status", "" + statusCode));
        return new Pair<Header[], HttpResponse>(headers.toArray(new Header[0]), response);
    } catch (HttpException e) {
        throw ServiceException.RESOURCE_UNREACHABLE("HttpException while fetching " + url, e);
    } catch (IOException e) {
        throw ServiceException.RESOURCE_UNREACHABLE("IOException while fetching " + url, e);
    }
}
Also used : RequestConfig(org.apache.http.client.config.RequestConfig) SocketConfig(org.apache.http.config.SocketConfig) ArrayList(java.util.ArrayList) HttpResponse(org.apache.http.HttpResponse) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) BasicClientCookie(org.apache.http.impl.cookie.BasicClientCookie) IOException(java.io.IOException) HttpPut(org.apache.http.client.methods.HttpPut) Mountpoint(com.zimbra.cs.mailbox.Mountpoint) InputStreamRequestHttpRetryHandler(com.zimbra.common.httpclient.InputStreamRequestHttpRetryHandler) BasicCookieStore(org.apache.http.impl.client.BasicCookieStore) AccountServiceException(com.zimbra.cs.account.AccountServiceException) ServiceException(com.zimbra.common.service.ServiceException) MailServiceException(com.zimbra.cs.mailbox.MailServiceException) Header(org.apache.http.Header) BasicHeader(org.apache.http.message.BasicHeader) HttpClient(org.apache.http.client.HttpClient) HttpException(org.apache.http.HttpException) Map(java.util.Map) HashMap(java.util.HashMap) BasicHeader(org.apache.http.message.BasicHeader) Pair(com.zimbra.common.util.Pair)

Example 35 with BasicClientCookie

use of org.apache.http.impl.cookie.BasicClientCookie in project zm-mailbox by Zimbra.

the class StatsImageServlet method doGet.

public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    AuthToken authToken = getAdminAuthTokenFromCookie(req, resp);
    if (authToken == null)
        return;
    String imgName = null;
    InputStream is = null;
    boolean imgAvailable = true;
    boolean localServer = false;
    boolean systemWide = false;
    String serverAddr = "";
    String noDefaultImg = req.getParameter("nodef");
    boolean noDefault = false;
    if (noDefaultImg != null && !noDefaultImg.equals("") && noDefaultImg.equals("1")) {
        noDefault = true;
    }
    String reqPath = req.getRequestURI();
    try {
        // check if this is the logger host, otherwise proxy the request to the logger host
        String serviceHostname = Provisioning.getInstance().getLocalServer().getAttr(Provisioning.A_zimbraServiceHostname);
        String logHost = Provisioning.getInstance().getConfig().getAttr(Provisioning.A_zimbraLogHostname);
        if (!serviceHostname.equalsIgnoreCase(logHost)) {
            StringBuffer url = new StringBuffer("https");
            url.append("://").append(logHost).append(':').append(LC.zimbra_admin_service_port.value());
            url.append(reqPath);
            String queryStr = req.getQueryString();
            if (queryStr != null)
                url.append('?').append(queryStr);
            // create an HTTP client with the same cookies
            BasicCookieStore cookieStore = new BasicCookieStore();
            try {
                BasicClientCookie cookie = new BasicClientCookie(ZimbraCookie.COOKIE_ZM_ADMIN_AUTH_TOKEN, authToken.getEncoded());
                cookie.setDomain(logHost);
                cookie.setPath("/");
                cookie.setSecure(false);
                cookieStore.addCookie(cookie);
            } catch (AuthTokenException ate) {
                throw ServiceException.PROXY_ERROR(ate, url.toString());
            }
            HttpClientBuilder clientBuilder = ZimbraHttpConnectionManager.getInternalHttpConnMgr().newHttpClient();
            clientBuilder.setDefaultCookieStore(cookieStore);
            HttpGet get = new HttpGet(url.toString());
            HttpClient client = clientBuilder.build();
            HttpResponse httpResp = null;
            try {
                httpResp = HttpClientUtil.executeMethod(client, get);
                int statusCode = httpResp.getStatusLine().getStatusCode();
                if (statusCode != HttpStatus.SC_OK)
                    throw ServiceException.RESOURCE_UNREACHABLE(httpResp.getStatusLine().getReasonPhrase(), null);
                resp.setContentType("image/gif");
                ByteUtil.copy(httpResp.getEntity().getContent(), true, resp.getOutputStream(), false);
                return;
            } catch (HttpException | IOException e) {
                throw ServiceException.RESOURCE_UNREACHABLE(httpResp.getStatusLine().getReasonPhrase(), e);
            } finally {
                EntityUtils.consumeQuietly(httpResp.getEntity());
            }
        }
    } catch (Exception ex) {
        resp.sendError(HttpServletResponse.SC_NOT_FOUND, "Image not found");
        return;
    }
    try {
        if (reqPath == null || reqPath.length() == 0) {
            resp.sendError(HttpServletResponse.SC_BAD_REQUEST);
            return;
        }
        if (mLog.isDebugEnabled())
            mLog.debug("received request to:(" + reqPath + ")");
        String[] reqParts = reqPath.split("/");
        String reqFilename = reqParts[3];
        imgName = LC.stats_img_folder.value() + File.separator + reqFilename;
        try {
            is = new FileInputStream(imgName);
        } catch (FileNotFoundException ex) {
            // unlikely case - only if the server's files are broken
            if (is != null)
                is.close();
            if (!noDefault) {
                imgName = LC.stats_img_folder.value() + File.separator + IMG_NOT_AVAIL;
                is = new FileInputStream(imgName);
            } else {
                resp.sendError(HttpServletResponse.SC_NOT_FOUND, "Image not found");
                return;
            }
        }
    } catch (Exception ex) {
        if (is != null)
            is.close();
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "FNF image File not found");
        return;
    }
    resp.setContentType("image/gif");
    ByteUtil.copy(is, true, resp.getOutputStream(), false);
}
Also used : FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) HttpGet(org.apache.http.client.methods.HttpGet) FileNotFoundException(java.io.FileNotFoundException) HttpResponse(org.apache.http.HttpResponse) BasicClientCookie(org.apache.http.impl.cookie.BasicClientCookie) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) IOException(java.io.IOException) ServletException(javax.servlet.ServletException) ServiceException(com.zimbra.common.service.ServiceException) IOException(java.io.IOException) AuthTokenException(com.zimbra.cs.account.AuthTokenException) FileNotFoundException(java.io.FileNotFoundException) HttpException(org.apache.http.HttpException) FileInputStream(java.io.FileInputStream) BasicCookieStore(org.apache.http.impl.client.BasicCookieStore) AuthTokenException(com.zimbra.cs.account.AuthTokenException) HttpClient(org.apache.http.client.HttpClient) AuthToken(com.zimbra.cs.account.AuthToken) HttpException(org.apache.http.HttpException)

Aggregations

BasicClientCookie (org.apache.http.impl.cookie.BasicClientCookie)88 BasicCookieStore (org.apache.http.impl.client.BasicCookieStore)36 Test (org.junit.Test)24 HttpResponse (org.apache.http.HttpResponse)19 Cookie (org.apache.http.cookie.Cookie)17 HttpClient (org.apache.http.client.HttpClient)15 HttpGet (org.apache.http.client.methods.HttpGet)15 HttpClientBuilder (org.apache.http.impl.client.HttpClientBuilder)15 Map (java.util.Map)14 RequestConfig (org.apache.http.client.config.RequestConfig)13 HttpPost (org.apache.http.client.methods.HttpPost)9 CookieAttributeHandler (org.apache.http.cookie.CookieAttributeHandler)9 CookieOrigin (org.apache.http.cookie.CookieOrigin)9 URL (java.net.URL)8 HttpEntity (org.apache.http.HttpEntity)8 CookieStore (org.apache.http.client.CookieStore)8 IOException (java.io.IOException)7 Date (java.util.Date)7 ClientCookie (org.apache.http.cookie.ClientCookie)7 HashMap (java.util.HashMap)6