cz.msebera.android.httpclient.HttpHost Java Examples

The following examples show how to use cz.msebera.android.httpclient.HttpHost. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: CloudflareChecker.java    From Overchan-Android with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Пройти анти-ддос проверку cloudflare
 * @param exception Cloudflare исключение
 * @param httpClient HTTP клиент
 * @param task отменяемая задача
 * @param activity активность, в контексте которого будет запущен WebView (webkit)
 * @return полученная cookie или null, если проверка не прошла по таймауту, или проверка уже проходит в другом потоке
 */
public Cookie checkAntiDDOS(CloudflareException exception, HttpClient httpClient, CancellableTask task, Activity activity) {
    if (exception.isRecaptcha()) throw new IllegalArgumentException();
    
    HttpHost proxy = null;
    if (httpClient instanceof ExtendedHttpClient) {
        proxy = ((ExtendedHttpClient) httpClient).getProxy();
    } else if (httpClient != null) {
        try {
            proxy = ConnRouteParams.getDefaultProxy(httpClient.getParams());
        } catch (Exception e) { /*ignore*/ }
    }
    if (proxy != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        if (httpClient instanceof ExtendedHttpClient) {
            return InterceptingAntiDDOS.getInstance().check(exception, (ExtendedHttpClient) httpClient, task, activity);
        } else {
            throw new IllegalArgumentException(
                    "cannot run anti-DDOS checking with proxy settings; http client is not instance of ExtendedHttpClient");
        }
    } else {
        return checkAntiDDOS(exception, proxy, task, activity);
    }
}
 
Example #2
Source File: HttpWebConnection.java    From HtmlUnit-Android with Apache License 2.0 6 votes vote down vote up
private void setProxy(final HttpRequestBase httpRequest, final WebRequest webRequest) {
    final InetAddress localAddress = webClient_.getOptions().getLocalAddress();
    final RequestConfig.Builder requestBuilder = createRequestConfigBuilder(getTimeout(), localAddress);

    if (webRequest.getProxyHost() != null) {
        final HttpHost proxy = new HttpHost(webRequest.getProxyHost(), webRequest.getProxyPort());
        if (webRequest.isSocksProxy()) {
            SocksConnectionSocketFactory.setSocksProxy(getHttpContext(), proxy);
        }
        else {
            requestBuilder.setProxy(proxy);
            httpRequest.setConfig(requestBuilder.build());
        }
    }
    else {
        requestBuilder.setProxy(null);
        httpRequest.setConfig(requestBuilder.build());
    }
}
 
Example #3
Source File: MainActivity.java    From httpclient-android with Apache License 2.0 5 votes vote down vote up
@Override
protected String doInBackground(Void... voids) {
    String ret = null;
    CloseableHttpClient chc = HttpClients.createDefault();
    try {
        CloseableHttpResponse chr = chc.execute(HttpHost.create("https://httpbin.org"), new HttpGet("/headers"));
        ret = EntityUtils.toString(chr.getEntity());
        chr.close();
        chc.close();
    } catch (Exception e) {
        Log.e("HttpTest", e.getMessage(), e);
        ret = e.getMessage();
    }
    return ret;
}
 
Example #4
Source File: SocksConnectionSocketFactory.java    From HtmlUnit-Android with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public Socket createSocket(final HttpContext context) throws IOException {
    final HttpHost socksProxy = getSocksProxy(context);
    if (socksProxy != null) {
        return createSocketWithSocksProxy(socksProxy);
    }
    return super.createSocket(context);
}
 
Example #5
Source File: RecaptchaAjax.java    From Overchan-Android with GNU General Public License v3.0 5 votes vote down vote up
static String getChallenge(String key, CancellableTask task, HttpClient httpClient, String scheme) throws Exception {
    if (scheme == null) scheme = "http";
    String address = scheme + "://127.0.0.1/";
    String data = "<script type=\"text/javascript\"> " +
                      "var RecaptchaOptions = { " +
                          "theme : 'custom', " +
                          "custom_theme_widget: 'recaptcha_widget' " +
                      "}; " +
                  "</script>" +
                  "<div id=\"recaptcha_widget\" style=\"display:none\"> " +
                      "<div id=\"recaptcha_image\"></div> " +
                      "<input type=\"text\" id=\"recaptcha_response_field\" name=\"recaptcha_response_field\" /> " +
                  "</div>" +
                  "<script type=\"text/javascript\" src=\"" + scheme + "://www.google.com/recaptcha/api/challenge?k=" + key + "\"></script>";
    
    HttpHost proxy = null;
    if (httpClient instanceof ExtendedHttpClient) {
        proxy = ((ExtendedHttpClient) httpClient).getProxy();
    } else if (httpClient != null) {
        try {
            proxy = ConnRouteParams.getDefaultProxy(httpClient.getParams());
        } catch (Exception e) { /*ignore*/ }
    }
    if (proxy != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        return Intercepting.getInternal(address, data, task, httpClient);
    } else {
        return getChallengeInternal(address, data, task, proxy);
    }
}
 
Example #6
Source File: HtmlUnitSSLConnectionSocketFactory.java    From HtmlUnit-Android with Apache License 2.0 5 votes vote down vote up
private static void setEmptyHostname(final HttpHost host) {
    try {
        final Field field = HttpHost.class.getDeclaredField("hostname");
        field.setAccessible(true);
        field.set(host, "");
    }
    catch (final Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example #7
Source File: ExtendedSSLSocketFactory.java    From Overchan-Android with GNU General Public License v3.0 5 votes vote down vote up
public Socket connectSocket(
        final int connectTimeout,
        final Socket socket,
        final HttpHost host,
        final InetSocketAddress remoteAddress,
        final InetSocketAddress localAddress,
        final HttpContext context) throws IOException {
    Args.notNull(host, "HTTP host");
    Args.notNull(remoteAddress, "Remote address");
    final Socket sock = socket != null ? socket : createSocket(context);
    if (localAddress != null) {
        sock.bind(localAddress);
    }
    try {
        if (connectTimeout > 0 && sock.getSoTimeout() == 0) {
            sock.setSoTimeout(connectTimeout);
        }
        sock.connect(remoteAddress, connectTimeout);
    } catch (final IOException ex) {
        try {
            sock.close();
        } catch (final IOException ignore) {
        }
        throw ex;
    }
    // Setup SSL layering if necessary
    if (sock instanceof SSLSocket) {
        final SSLSocket sslsock = (SSLSocket) sock;
        sslsock.startHandshake();
        verifyHostname(sslsock, host.getHostName());
        return sock;
    } else {
        return createLayeredSocket(sock, host.getHostName(), remoteAddress.getPort(), context);
    }
}
 
Example #8
Source File: ExtendedHttpClient.java    From Overchan-Android with GNU General Public License v3.0 5 votes vote down vote up
private static HttpClient build(final HttpHost proxy, CookieStore cookieStore) {
    SSLCompatibility.waitIfInstallingAsync();
    return HttpClients.custom().
            setDefaultRequestConfig(getDefaultRequestConfigBuilder(HttpConstants.DEFAULT_HTTP_TIMEOUT).build()).
            setUserAgent(HttpConstants.USER_AGENT_STRING).
            setProxy(proxy).
            setDefaultCookieStore(cookieStore).
            setSSLSocketFactory(ExtendedSSLSocketFactory.getSocketFactory()).
            build();
}
 
Example #9
Source File: ExtendedHttpClient.java    From Overchan-Android with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Получить значение HTTP-прокси данного экземпляра
 */
public HttpHost getProxy() {
    return proxy;
}
 
Example #10
Source File: RecaptchaAjax.java    From Overchan-Android with GNU General Public License v3.0 4 votes vote down vote up
private static String getChallengeInternal(final String address, final String data, CancellableTask task, final HttpHost proxy) throws Exception {
    Logger.d(TAG, "not intercepting; proxy: " + (proxy == null ? "disabled" : "enabled"));
    if (proxy != null) {
        Logger.d(TAG, "AJAX recaptcha not using (proxy and old API)");
        throw new Exception("proxy && old API");
        //костыль с установкой прокси через reflection не используется, т.к. в отличие от js-antiddos, здесь не критично (получит noscript капчу)
    }
    final Context context = MainApplication.getInstance();
    final Holder holder = new Holder();
    
    Async.runOnUiThread(new Runnable() {
        @SuppressLint("SetJavaScriptEnabled")
        @Override
        public void run() {
            holder.webView = new WebView(context);
            holder.webView.setWebViewClient(new WebViewClient() {
                @Override
                public void onLoadResource(WebView view, String url) {
                    String challenge = getChallengeFromImageUrl(url);
                    if (challenge != null) holder.challenge = challenge;
                    super.onLoadResource(view, url);
                }
            });
            holder.webView.getSettings().setUserAgentString(CUSTOM_UA);
            holder.webView.getSettings().setJavaScriptEnabled(true);
            holder.webView.loadDataWithBaseURL(address, data, "text/html", "UTF-8", null);
        }
    });
    
    long startTime = System.currentTimeMillis();
    while (holder.challenge == null) {
        long time = System.currentTimeMillis() - startTime;
        if ((task != null && task.isCancelled()) || time > TIMEOUT) break;
        Thread.yield();
    }
    
    Async.runOnUiThread(new Runnable() {
        @Override
        public void run() {
            try {
                holder.webView.stopLoading();
                holder.webView.clearCache(true);
                holder.webView.destroy();
            } catch (Exception e) {
                Logger.e(TAG, e);
            }
        }
    });
    
    if (holder.challenge == null) throw new RecaptchaException("couldn't get Recaptcha Challenge (AJAX)");
    return holder.challenge;
}
 
Example #11
Source File: HttpClientWrapper.java    From Overchan-Android with GNU General Public License v3.0 4 votes vote down vote up
@Override
public <T> T execute(HttpHost target, HttpRequest request, ResponseHandler<? extends T> responseHandler, HttpContext context)
        throws IOException, ClientProtocolException {
    return getClient().execute(target, request, responseHandler, context);
}
 
Example #12
Source File: HttpClientWrapper.java    From Overchan-Android with GNU General Public License v3.0 4 votes vote down vote up
@Override
public <T> T execute(HttpHost target, HttpRequest request, ResponseHandler<? extends T> responseHandler)
        throws IOException, ClientProtocolException {
    return getClient().execute(target, request, responseHandler);
}
 
Example #13
Source File: HttpClientWrapper.java    From Overchan-Android with GNU General Public License v3.0 4 votes vote down vote up
@Override
public HttpResponse execute(HttpHost target, HttpRequest request, HttpContext context) throws IOException, ClientProtocolException {
    return getClient().execute(target, request, context);
}
 
Example #14
Source File: HttpClientWrapper.java    From Overchan-Android with GNU General Public License v3.0 4 votes vote down vote up
@Override
public HttpResponse execute(HttpHost target, HttpRequest request) throws IOException, ClientProtocolException {
    return getClient().execute(target, request);
}
 
Example #15
Source File: ExtendedHttpClient.java    From Overchan-Android with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Конструктор
 * @param proxy адрес HTTP прокси (возможно null)
 */
public ExtendedHttpClient(HttpHost proxy) {
    super();
    this.cookieStore = new BasicCookieStore();
    this.proxy = proxy;
}
 
Example #16
Source File: HttpWebConnection.java    From HtmlUnit-Android with Apache License 2.0 4 votes vote down vote up
@Override
public synchronized void remove(final HttpHost host) {
    super.remove(host);
}
 
Example #17
Source File: HttpWebConnection.java    From HtmlUnit-Android with Apache License 2.0 4 votes vote down vote up
@Override
public synchronized AuthScheme get(final HttpHost host) {
    return super.get(host);
}
 
Example #18
Source File: HttpWebConnection.java    From HtmlUnit-Android with Apache License 2.0 4 votes vote down vote up
@Override
public synchronized void put(final HttpHost host, final AuthScheme authScheme) {
    super.put(host, authScheme);
}
 
Example #19
Source File: HtmlUnitSSLConnectionSocketFactory.java    From HtmlUnit-Android with Apache License 2.0 4 votes vote down vote up
/**
 * Connect via socket.
 * @param connectTimeout the timeout
 * @param socket the socket
 * @param host the host
 * @param remoteAddress the remote address
 * @param localAddress the local address
 * @param context the context
 * @return the created/connected socket
 * @throws IOException in case of problems
 */
@Override
public Socket connectSocket(
        final int connectTimeout,
        final Socket socket,
        final HttpHost host,
        final InetSocketAddress remoteAddress,
        final InetSocketAddress localAddress,
        final HttpContext context) throws IOException {
    final HttpHost socksProxy = SocksConnectionSocketFactory.getSocksProxy(context);
    if (socksProxy != null) {
        final Socket underlying = SocksConnectionSocketFactory.createSocketWithSocksProxy(socksProxy);
        underlying.setReuseAddress(true);

        final SocketAddress socksProxyAddress = new InetSocketAddress(socksProxy.getHostName(),
                socksProxy.getPort());
        try {
            //underlying.setSoTimeout(soTimeout);
            underlying.connect(remoteAddress, connectTimeout);
        }
        catch (final SocketTimeoutException ex) {
            throw new ConnectTimeoutException("Connect to " + socksProxyAddress + " timed out");
        }

        final Socket sslSocket = getSSLSocketFactory().createSocket(underlying, socksProxy.getHostName(),
                socksProxy.getPort(), true);
        configureSocket((SSLSocket) sslSocket, context);
        return sslSocket;
    }
    try {
        return super.connectSocket(connectTimeout, socket, host, remoteAddress, localAddress, context);
    }
    catch (final IOException e) {
        if (useInsecureSSL_ && "handshake alert:  unrecognized_name".equals(e.getMessage())) {
            setEmptyHostname(host);

            return super.connectSocket(connectTimeout,
                    createSocket(context),
                    host, remoteAddress, localAddress, context);
        }
        throw e;
    }
}
 
Example #20
Source File: SocksConnectionSocketFactory.java    From HtmlUnit-Android with Apache License 2.0 4 votes vote down vote up
static Socket createSocketWithSocksProxy(final HttpHost socksProxy) {
    final InetSocketAddress address = new InetSocketAddress(socksProxy.getHostName(), socksProxy.getPort());
    final Proxy proxy = new Proxy(Proxy.Type.SOCKS, address);
    return new Socket(proxy);
}
 
Example #21
Source File: SocksConnectionSocketFactory.java    From HtmlUnit-Android with Apache License 2.0 4 votes vote down vote up
static HttpHost getSocksProxy(final HttpContext context) {
    return (HttpHost) context.getAttribute(SOCKS_PROXY);
}
 
Example #22
Source File: SocksConnectionSocketFactory.java    From HtmlUnit-Android with Apache License 2.0 2 votes vote down vote up
/**
 * Enables the socks proxy.
 * @param context the HttpContext
 * @param socksProxy the HttpHost
 */
public static void setSocksProxy(final HttpContext context, final HttpHost socksProxy) {
    context.setAttribute(SOCKS_PROXY, socksProxy);
}
 
Example #23
Source File: HttpWebConnection.java    From HtmlUnit-Android with Apache License 2.0 2 votes vote down vote up
/**
 * Returns a new HttpClient host configuration, initialized based on the specified request.
 * @param webRequest the request to use to initialize the returned host configuration
 * @return a new HttpClient host configuration, initialized based on the specified request
 */
private static HttpHost getHostConfiguration(final WebRequest webRequest) {
    final URL url = webRequest.getUrl();
    return new HttpHost(url.getHost(), url.getPort(), url.getProtocol());
}