Search in sources :

Example 21 with BasicHttpContext

use of org.apache.http.protocol.BasicHttpContext in project dropwizard by dropwizard.

the class HttpClientBuilderTest method checkProxy.

private CloseableHttpClient checkProxy(HttpClientConfiguration config, HttpHost target, @Nullable HttpHost expectedProxy) throws Exception {
    CloseableHttpClient httpClient = builder.using(config).build("test");
    HttpRoutePlanner routePlanner = (HttpRoutePlanner) getInaccessibleField(httpClient.getClass(), "routePlanner").get(httpClient);
    HttpRoute route = routePlanner.determineRoute(target, new HttpGet(target.toURI()), new BasicHttpContext());
    assertThat(route.getProxyHost()).isEqualTo(expectedProxy);
    assertThat(route.getTargetHost()).isEqualTo(target);
    assertThat(route.getHopCount()).isEqualTo(expectedProxy != null ? 2 : 1);
    return httpClient;
}
Also used : CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) HttpRoute(org.apache.http.conn.routing.HttpRoute) HttpRoutePlanner(org.apache.http.conn.routing.HttpRoutePlanner) BasicHttpContext(org.apache.http.protocol.BasicHttpContext) HttpGet(org.apache.http.client.methods.HttpGet)

Example 22 with BasicHttpContext

use of org.apache.http.protocol.BasicHttpContext in project Anki-Android by Ramblurr.

the class HttpFetcher method fetchThroughHttp.

public static String fetchThroughHttp(String address, String encoding) {
    try {
        HttpClient httpClient = new DefaultHttpClient();
        HttpContext localContext = new BasicHttpContext();
        HttpGet httpGet = new HttpGet(address);
        HttpResponse response = httpClient.execute(httpGet, localContext);
        if (!response.getStatusLine().toString().contains("OK")) {
            return "FAILED";
        }
        BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), Charset.forName(encoding)));
        StringBuilder stringBuilder = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            stringBuilder.append(line);
        }
        return stringBuilder.toString();
    } catch (Exception e) {
        return "FAILED with exception: " + e.getMessage();
    }
}
Also used : InputStreamReader(java.io.InputStreamReader) BasicHttpContext(org.apache.http.protocol.BasicHttpContext) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) HttpClient(org.apache.http.client.HttpClient) HttpGet(org.apache.http.client.methods.HttpGet) BasicHttpContext(org.apache.http.protocol.BasicHttpContext) HttpContext(org.apache.http.protocol.HttpContext) BufferedReader(java.io.BufferedReader) HttpResponse(org.apache.http.HttpResponse) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient)

Example 23 with BasicHttpContext

use of org.apache.http.protocol.BasicHttpContext in project Fling by entertailion.

the class RampClient method closeCurrentApp.

public void closeCurrentApp() {
    if (dialServer != null) {
        try {
            DefaultHttpClient defaultHttpClient = HttpRequestHelper.createHttpClient();
            CustomRedirectHandler handler = new CustomRedirectHandler();
            defaultHttpClient.setRedirectHandler(handler);
            BasicHttpContext localContext = new BasicHttpContext();
            // check if any app is running
            HttpGet httpGet = new HttpGet(dialServer.getAppsUrl());
            httpGet.setHeader(HEADER_CONNECTION, HEADER_CONNECTION_VALUE);
            httpGet.setHeader(HEADER_USER_AGENT, HEADER_USER_AGENT_VALUE);
            httpGet.setHeader(HEADER_ACCEPT, HEADER_ACCEPT_VALUE);
            httpGet.setHeader(HEADER_DNT, HEADER_DNT_VALUE);
            httpGet.setHeader(HEADER_ACCEPT_ENCODING, HEADER_ACCEPT_ENCODING_VALUE);
            httpGet.setHeader(HEADER_ACCEPT_LANGUAGE, HEADER_ACCEPT_LANGUAGE_VALUE);
            HttpResponse httpResponse = defaultHttpClient.execute(httpGet);
            if (httpResponse != null) {
                int responseCode = httpResponse.getStatusLine().getStatusCode();
                Log.d(LOG_TAG, "get response code=" + httpResponse.getStatusLine().getStatusCode());
                if (responseCode == 204) {
                // nothing is running
                } else if (responseCode == 200) {
                    // app is running
                    // Need to get real URL after a redirect
                    // http://stackoverflow.com/a/10286025/594751
                    String lastUrl = dialServer.getAppsUrl();
                    if (handler.lastRedirectedUri != null) {
                        lastUrl = handler.lastRedirectedUri.toString();
                        Log.d(LOG_TAG, "lastUrl=" + lastUrl);
                    }
                    String response = EntityUtils.toString(httpResponse.getEntity());
                    Log.d(LOG_TAG, "get response=" + response);
                    parseXml(new StringReader(response));
                    Header[] headers = httpResponse.getAllHeaders();
                    for (int i = 0; i < headers.length; i++) {
                        Log.d(LOG_TAG, headers[i].getName() + "=" + headers[i].getValue());
                    }
                    // stop the app instance
                    HttpDelete httpDelete = new HttpDelete(lastUrl);
                    httpResponse = defaultHttpClient.execute(httpDelete);
                    if (httpResponse != null) {
                        Log.d(LOG_TAG, "delete response code=" + httpResponse.getStatusLine().getStatusCode());
                        response = EntityUtils.toString(httpResponse.getEntity());
                        Log.d(LOG_TAG, "delete response=" + response);
                    } else {
                        Log.d(LOG_TAG, "no delete response");
                    }
                }
            } else {
                Log.i(LOG_TAG, "no get response");
                return;
            }
        } catch (Exception e) {
            Log.e(LOG_TAG, "closeCurrentApp", e);
        }
    }
}
Also used : HttpDelete(org.apache.http.client.methods.HttpDelete) BasicHttpContext(org.apache.http.protocol.BasicHttpContext) HttpGet(org.apache.http.client.methods.HttpGet) StringReader(java.io.StringReader) HttpResponse(org.apache.http.HttpResponse) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) ProtocolException(org.apache.http.ProtocolException)

Example 24 with BasicHttpContext

use of org.apache.http.protocol.BasicHttpContext in project undertow by undertow-io.

the class SimpleConfidentialRedirectTestCase method simpleRedirectTestCase.

@Test
public void simpleRedirectTestCase() throws IOException, GeneralSecurityException {
    TestHttpClient client = new TestHttpClient();
    // create our own context to force http-request.config
    // notice that, if we just create http context, the config is ovewritten before request is sent
    // if we add the config to the HttpClient instead, it is ignored
    HttpContext httpContext = new BasicHttpContext() {

        private final RequestConfig config = RequestConfig.copy(RequestConfig.DEFAULT).setNormalizeUri(false).build();

        @Override
        public void setAttribute(final String id, final Object obj) {
            if ("http.request-config".equals(id))
                return;
            super.setAttribute(id, obj);
        }

        @Override
        public Object getAttribute(final String id) {
            if ("http.request-config".equals(id))
                return config;
            return super.getAttribute(id);
        }
    };
    client.setSSLContext(DefaultServer.getClientSSLContext());
    try {
        sendRequest(client, httpContext, "/foo", null);
        sendRequest(client, httpContext, "/foo+bar", null);
        sendRequest(client, httpContext, "/foo+bar;aa", null);
        sendRequest(client, httpContext, "/foo+bar;aa", "x=y");
        sendRequest(client, httpContext, "/foo+bar%3Aaa", "x=%3Ablah");
    } finally {
        client.getConnectionManager().shutdown();
    }
}
Also used : RequestConfig(org.apache.http.client.config.RequestConfig) BasicHttpContext(org.apache.http.protocol.BasicHttpContext) BasicHttpContext(org.apache.http.protocol.BasicHttpContext) HttpContext(org.apache.http.protocol.HttpContext) HttpString(io.undertow.util.HttpString) TestHttpClient(io.undertow.testutils.TestHttpClient) Test(org.junit.Test)

Example 25 with BasicHttpContext

use of org.apache.http.protocol.BasicHttpContext in project SmartAndroidSource by jaychou2012.

the class AbstractAjaxCallback method httpDo.

private void httpDo(HttpUriRequest hr, String url, Map<String, String> headers, AjaxStatus status) throws ClientProtocolException, IOException {
    if (AGENT != null) {
        hr.addHeader("User-Agent", AGENT);
    }
    if (headers != null) {
        for (String name : headers.keySet()) {
            hr.addHeader(name, headers.get(name));
        }
    }
    if (GZIP && (headers == null || !headers.containsKey("Accept-Encoding"))) {
        hr.addHeader("Accept-Encoding", "gzip");
    }
    String cookie = makeCookie();
    if (cookie != null) {
        hr.addHeader("Cookie", cookie);
    }
    if (ah != null) {
        ah.applyToken(this, hr);
    }
    DefaultHttpClient client = getClient();
    HttpParams hp = hr.getParams();
    if (proxy != null)
        hp.setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
    if (timeout > 0) {
        AQUtility.debug("timeout param", CoreConnectionPNames.CONNECTION_TIMEOUT);
        hp.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, timeout);
        hp.setParameter(CoreConnectionPNames.SO_TIMEOUT, timeout);
    }
    HttpContext context = new BasicHttpContext();
    CookieStore cookieStore = new BasicCookieStore();
    context.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
    request = hr;
    if (abort) {
        throw new IOException("Aborted");
    }
    HttpResponse response = client.execute(hr, context);
    byte[] data = null;
    String redirect = url;
    int code = response.getStatusLine().getStatusCode();
    String message = response.getStatusLine().getReasonPhrase();
    String error = null;
    HttpEntity entity = response.getEntity();
    Header[] hs = response.getAllHeaders();
    HashMap<String, String> responseHeaders = new HashMap<String, String>(hs.length);
    for (Header h : hs) {
        responseHeaders.put(h.getName(), h.getValue());
    }
    setResponseHeaders(responseHeaders);
    File file = null;
    if (code < 200 || code >= 300) {
        try {
            if (entity != null) {
                InputStream is = entity.getContent();
                byte[] s = toData(getEncoding(entity), is);
                error = new String(s, "UTF-8");
                AQUtility.debug("error", error);
            }
        } catch (Exception e) {
            AQUtility.debug(e);
        }
    } else {
        HttpHost currentHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
        HttpUriRequest currentReq = (HttpUriRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST);
        redirect = currentHost.toURI() + currentReq.getURI();
        int size = Math.max(32, Math.min(1024 * 64, (int) entity.getContentLength()));
        OutputStream os = null;
        InputStream is = null;
        try {
            file = getPreFile();
            if (file == null) {
                os = new PredefinedBAOS(size);
            } else {
                file.createNewFile();
                os = new BufferedOutputStream(new FileOutputStream(file));
            }
            // AQUtility.time("copy");
            copy(entity.getContent(), os, getEncoding(entity), (int) entity.getContentLength());
            // AQUtility.timeEnd("copy", 0);
            os.flush();
            if (file == null) {
                data = ((PredefinedBAOS) os).toByteArray();
            } else {
                if (!file.exists() || file.length() == 0) {
                    file = null;
                }
            }
        } finally {
            AQUtility.close(is);
            AQUtility.close(os);
        }
    }
    AQUtility.debug("response", code);
    if (data != null) {
        AQUtility.debug(data.length, url);
    }
    status.code(code).message(message).error(error).redirect(redirect).time(new Date()).data(data).file(file).client(client).context(context).headers(response.getAllHeaders());
}
Also used : HttpUriRequest(org.apache.http.client.methods.HttpUriRequest) HttpEntity(org.apache.http.HttpEntity) HashMap(java.util.HashMap) BasicHttpContext(org.apache.http.protocol.BasicHttpContext) DataOutputStream(java.io.DataOutputStream) BufferedOutputStream(java.io.BufferedOutputStream) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) HttpHost(org.apache.http.HttpHost) BufferedOutputStream(java.io.BufferedOutputStream) GZIPInputStream(java.util.zip.GZIPInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) BasicHttpContext(org.apache.http.protocol.BasicHttpContext) HttpContext(org.apache.http.protocol.HttpContext) HttpResponse(org.apache.http.HttpResponse) IOException(java.io.IOException) ClientProtocolException(org.apache.http.client.ClientProtocolException) IOException(java.io.IOException) Date(java.util.Date) CookieStore(org.apache.http.client.CookieStore) BasicCookieStore(org.apache.http.impl.client.BasicCookieStore) BasicHttpParams(org.apache.http.params.BasicHttpParams) HttpParams(org.apache.http.params.HttpParams) BasicCookieStore(org.apache.http.impl.client.BasicCookieStore) Header(org.apache.http.Header) FileOutputStream(java.io.FileOutputStream) File(java.io.File)

Aggregations

BasicHttpContext (org.apache.http.protocol.BasicHttpContext)60 HttpContext (org.apache.http.protocol.HttpContext)37 IOException (java.io.IOException)24 HttpResponse (org.apache.http.HttpResponse)21 HttpGet (org.apache.http.client.methods.HttpGet)19 BasicCookieStore (org.apache.http.impl.client.BasicCookieStore)14 HttpHost (org.apache.http.HttpHost)11 DefaultHttpClient (org.apache.http.impl.client.DefaultHttpClient)11 HttpEntity (org.apache.http.HttpEntity)10 HttpPost (org.apache.http.client.methods.HttpPost)10 CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)10 Header (org.apache.http.Header)8 BasicScheme (org.apache.http.impl.auth.BasicScheme)8 InputStream (java.io.InputStream)7 AuthScope (org.apache.http.auth.AuthScope)7 HttpUriRequest (org.apache.http.client.methods.HttpUriRequest)7 URI (java.net.URI)6 ArrayList (java.util.ArrayList)6 GZIPInputStream (java.util.zip.GZIPInputStream)6 UsernamePasswordCredentials (org.apache.http.auth.UsernamePasswordCredentials)6