Example usage for org.apache.http.protocol HttpContext getAttribute

List of usage examples for org.apache.http.protocol HttpContext getAttribute

Introduction

In this page you can find the example usage for org.apache.http.protocol HttpContext getAttribute.

Prototype

Object getAttribute(String str);

Source Link

Usage

From source file:wuit.common.crawler.WebSit.Crawler.java

public static String doGetHttp(DSCrawlerUrl pageUrl) {
    HttpParams params = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(params, 12000);
    HttpConnectionParams.setSoTimeout(params, 9000);
    HttpClient httpclient = new DefaultHttpClient(params);
    String rs = "";
    try {/*w w w.ja  v a 2 s.  co m*/
        HttpGet httpget = new HttpGet(pageUrl.url);
        //            System.out.println("executing request " + pageUrl.url);
        HttpContext httpContext = new BasicHttpContext();
        //            httpget.addHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)");
        httpget.addHeader("User-Agent",
                "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; QQDownload 1.7; .NET CLR 1.1.4322; CIBA; .NET CLR 2.0.50727)");

        HttpResponse response = httpclient.execute(httpget, httpContext);
        HttpUriRequest realRequest = (HttpUriRequest) httpContext.getAttribute(ExecutionContext.HTTP_REQUEST);
        HttpHost targetHost = (HttpHost) httpContext.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
        pageUrl.url = targetHost.toString() + realRequest.getURI();
        int resStatu = response.getStatusLine().getStatusCode();//? 
        if (resStatu == 200) {
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                rs = EntityUtils.toString(entity, "iso-8859-1");
                String in_code = getEncoding(rs);
                String encode = getHtmlEncode(rs);
                if (encode.isEmpty()) {
                    httpclient.getConnectionManager().shutdown();
                    return "";
                } else {
                    if (!in_code.toLowerCase().equals("utf-8")
                            && !in_code.toLowerCase().equals(encode.toLowerCase())) {
                        if (!in_code.toLowerCase().equals("iso-8859-1"))
                            rs = new String(rs.getBytes("iso-8859-1"), in_code);
                        if (!encode.toLowerCase().equals(in_code.toLowerCase()))
                            rs = new String(rs.getBytes(in_code), encode);
                    }
                }
                try {
                } catch (RuntimeException ex) {
                    httpget.abort();
                    throw ex;
                } finally {
                    // Closing the input stream will trigger connection release
                    //                    try { instream.close(); } catch (Exception ignore) {}
                }
            }
        }
    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();
        return rs;
    }
}

From source file:wuit.common.crawler.search.Crawler.java

public static String doGetHttp(String url) {
    HttpParams params = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(params, 12000);
    HttpConnectionParams.setSoTimeout(params, 9000);
    HttpClient httpclient = new DefaultHttpClient(params);
    String rs = "";
    try {/*  ww w. java2  s. c o  m*/
        //            System.out.println(url);
        HttpGet httpget = new HttpGet(url);

        HttpContext httpContext = new BasicHttpContext();
        //            httpget.addHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)");
        httpget.addHeader("User-Agent",
                "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; QQDownload 1.7; .NET CLR 1.1.4322; CIBA; .NET CLR 2.0.50727)");

        HttpResponse response = httpclient.execute(httpget, httpContext);
        HttpUriRequest realRequest = (HttpUriRequest) httpContext.getAttribute(ExecutionContext.HTTP_REQUEST);
        HttpHost targetHost = (HttpHost) httpContext.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
        url = targetHost.toString() + realRequest.getURI();
        int resStatu = response.getStatusLine().getStatusCode();//? 
        if (resStatu == 200) {
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                rs = EntityUtils.toString(entity, "iso-8859-1");
                String in_code = getEncoding(rs);
                String encode = getHtmlEncode(rs);
                if (encode.isEmpty()) {
                    httpclient.getConnectionManager().shutdown();
                    return "";
                } else {
                    if (!in_code.toLowerCase().equals("utf-8")
                            && !in_code.toLowerCase().equals(encode.toLowerCase())) {
                        if (!in_code.toLowerCase().equals("iso-8859-1"))
                            rs = new String(rs.getBytes("iso-8859-1"), in_code);
                        if (!encode.toLowerCase().equals(in_code.toLowerCase()))
                            rs = new String(rs.getBytes(in_code), encode);
                    }
                }
                try {
                } catch (RuntimeException ex) {
                    httpget.abort();
                    throw ex;
                } finally {
                    // Closing the input stream will trigger connection release
                    //                    try { instream.close(); } catch (Exception ignore) {}
                }
            }
        }
    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();
        return rs;
    }
}

From source file:eu.thecoder4.gpl.pleftdroid.PleftBroker.java

/**
 * @return Returns SC_CLIREDIR if the client is being redirected (eg. for net authentication)
 *         or SC_NOTPLEFTSERV if the server is not Pleft Server
 *         or HttpStatus.SC_OK if everything is OK
 *///from w  w w. j av  a  2s .co  m
protected static int checkServer(String pserver) {
    DefaultHttpClient client = getDefaultClient();
    HttpContext context = new BasicHttpContext();
    //We request the index
    HttpGet request = new HttpGet(pserver);
    HttpResponse response = null;
    try {
        response = client.execute(request, context);
        int SC = response.getStatusLine().getStatusCode();
        Log.i("PB", "checkServ SC:" + SC);
    } catch (Exception e) {
        return SC_TIMEOUT;
    }
    HttpHost currentHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);

    String host = currentHost.getHostName();

    Log.i("PB", "checkServ finalhost=" + host + "==" + getHostName(pserver) + "=pserverhost ? "
            + host.equals(getHostName(pserver)));
    if (!host.equals(getHostName(pserver))) {
        try {
            response.getEntity().getContent().close(); //You need to open and close the IS to release the connection !!!
        } catch (Exception e) {
        }
        return SC_CLIREDIR;
    }
    //InputStream is;
    try {
        String html = EntityUtils.toString(response.getEntity()); //It consumes content !
        if (html.contains("Pleft")) {
            return HttpStatus.SC_OK;
        } else {
            Log.i("PB", "checkServ NOPLEFT!");
            return SC_NOTPLEFTSERV;
        }
    } catch (Exception e) {
        Log.i("PB", "checkServ Got exception2:" + e);
        return SC_NOTPLEFTSERV;
    }

}

From source file:org.opendatakit.dwc.server.GreetingServiceImpl.java

public static final void clearAllCredentials() {
    HttpContext localContext = getHttpContext();
    CredentialsProvider credsProvider = (CredentialsProvider) localContext
            .getAttribute(ClientContext.CREDS_PROVIDER);
    credsProvider.clear();//from  ww w  .jav a  2  s. c  o m
}

From source file:com.oakley.fon.util.HttpUtils.java

public static HttpResult getUrl(String url, int maxRetries) throws IOException {
    String result = null;//ww  w.j a  v  a2 s  .c o m
    int retries = 0;
    HttpContext localContext = new BasicHttpContext();
    DefaultHttpClient httpclient = getHttpClient();

    HttpGet httpget = new HttpGet(url);
    while (retries <= maxRetries && result == null) {
        try {
            retries++;
            HttpEntity entity = httpclient.execute(httpget, localContext).getEntity();

            if (entity != null) {
                result = EntityUtils.toString(entity).trim();
            }
        } catch (SocketException se) {
            if (retries > maxRetries) {
                throw se;
            } else {
                Log.v(TAG, "SocketException, retrying " + retries);
            }
        }
    }

    return new HttpResult(result, (BasicHttpResponse) localContext.getAttribute("http.response"),
            ((HttpHost) localContext.getAttribute("http.target_host")).toURI());
}

From source file:org.opendatakit.dwc.server.GreetingServiceImpl.java

private static HttpRequestInterceptor getPreemptiveAuth() {
    return new HttpRequestInterceptor() {
        public void process(final HttpRequest request, final HttpContext context)
                throws HttpException, IOException {
            AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);
            CredentialsProvider credsProvider = (CredentialsProvider) context
                    .getAttribute(ClientContext.CREDS_PROVIDER);
            HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);

            if (authState.getAuthScheme() == null) {
                AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort());
                Credentials creds = credsProvider.getCredentials(authScope);
                if (creds != null) {
                    authState.setAuthScheme(new BasicScheme());
                    authState.setCredentials(creds);
                }//from   w  w w .  j  av  a  2s  . c  om
            }
        }
    };
}

From source file:com.joyent.manta.http.HttpContextRetryCancellation.java

/**
 * Check if the given context contains the reserved key and it is enabled.
 *
 * @param context the context to check/*from   w w w . j  a va  2 s  .c  o m*/
 * @return whether or not retries are disabled
 */
default boolean neverRetry(final HttpContext context) {
    final Object disableRetry = context.getAttribute(CONTEXT_ATTRIBUTE_MANTA_RETRY_DISABLE);

    return disableRetry instanceof Boolean && (Boolean) disableRetry;
}

From source file:com.sonatype.nexus.ssl.plugin.internal.HttpContextAttributeSSLContextSelector.java

@Override
public SSLContext select(final HttpContext context) {
    Object useTrustStore = context.getAttribute(SSLContextSelector.USE_TRUST_STORE);
    if (Boolean.TRUE.equals(useTrustStore)) {
        return trustStore.getSSLContext();
    }/*from  w  w w.j  a  va 2  s.co  m*/
    return null;
}

From source file:org.apache.olingo.samples.client.core.http.StatefulHttpClientFactory.java

@Override
public DefaultHttpClient create(final HttpMethod method, final URI uri) {
    final DefaultHttpClient httpClient = super.create(method, uri);

    httpClient.setUserTokenHandler(new UserTokenHandler() {

        @Override/*  w ww  .j  a v a2s.  c  o m*/
        public Object getUserToken(final HttpContext context) {
            return context.getAttribute("my-token");
        }

    });

    return httpClient;
}

From source file:org.apache.brooklyn.util.core.http.AuthHandler.java

@Override
public void handle(HttpRequest request, HttpResponse response, HttpContext context) {
    String creds = (String) context.getAttribute("creds");
    if (creds == null || !creds.equals(getExpectedCredentials())) {
        response.setStatusCode(HttpStatus.SC_UNAUTHORIZED);
    } else {//  w  w  w  .j a v a2  s  .c o  m
        response.setEntity(new ByteArrayEntity(responseBody));
    }
}