cz.msebera.android.httpclient.client.HttpClient Java Examples

The following examples show how to use cz.msebera.android.httpclient.client.HttpClient. 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: RecaptchaNoscript.java    From Overchan-Android with GNU General Public License v3.0 6 votes vote down vote up
static String getChallenge(String publicKey, CancellableTask task, HttpClient httpClient, String scheme) throws Exception {
    if (scheme == null) scheme = "http";
    String response = HttpStreamer.getInstance().getStringFromUrl(scheme + RECAPTCHA_CHALLENGE_URL + publicKey,
            HttpRequestModel.DEFAULT_GET, httpClient, null, task, false);
    Matcher matcher = CHALLENGE_FIRST_PATTERN.matcher(response);
    if (matcher.find()) {
        String challenge = matcher.group(1);
        try {
            response = HttpStreamer.getInstance().getStringFromUrl(scheme + RECAPTCHA_RELOAD_URL + challenge + "&k=" + publicKey,
                    HttpRequestModel.DEFAULT_GET, httpClient, null, task, false);
            matcher = CHALLENGE_RELOAD_PATTERN.matcher(response);
            if (matcher.find()) {
                String newChallenge = matcher.group(1);
                if (newChallenge != null && newChallenge.length() > 0) return newChallenge;
            }
        } catch (Exception e) {
            Logger.e(TAG, e);
        }
        
        return challenge;
    }
    throw new RecaptchaException("can't parse recaptcha challenge answer");
}
 
Example #2
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 #3
Source File: NetWorkTool.java    From FoodOrdering with Apache License 2.0 6 votes vote down vote up
public static String getContent(String url) throws Exception {
    StringBuilder sb = new StringBuilder();

    HttpClient client = new DefaultHttpClient();
    HttpParams httpParams = (HttpParams) client.getParams();
    // 设置网络超时参数
    HttpConnectionParams.setConnectionTimeout(httpParams, 3000);
    HttpConnectionParams.setSoTimeout(httpParams, 5000);
    HttpResponse response = client.execute(new HttpGet(url));
    HttpEntity entity = response.getEntity();
    if (entity != null) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                entity.getContent(), "GBK"), 8192);
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
        reader.close();
    }
    return sb.toString();
}
 
Example #4
Source File: AbstractVichanModule.java    From Overchan-Android with GNU General Public License v3.0 6 votes vote down vote up
public static List<Pair<String, String>> getFormValues(String url, HttpRequestModel requestModel, CancellableTask task, HttpClient client,
        String startForm, String endForm) throws Exception {
    VichanAntiBot reader = null;
    HttpRequestModel request = requestModel;
    HttpResponseModel response = null;
    try {
        response = HttpStreamer.getInstance().getFromUrl(url, request, client, null, task);
        reader = new VichanAntiBot(response.stream, startForm, endForm);
        return reader.readForm();
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (Exception e) {}
        }
        if (response != null) response.release();
    } 
}
 
Example #5
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 #6
Source File: PonyachModule.java    From Overchan-Android with GNU General Public License v3.0 5 votes vote down vote up
private Bitmap getBitmap(String url, CancellableTask task) throws HttpRequestException {
    PonyachModule thisModule = ((PonyachModule) MainApplication.getInstance().getChanModule(CHAN_NAME));
    String baseUrl = thisModule.getUsingUrl();
    if (url.startsWith("/")) url = baseUrl + url.substring(1);
    HttpClient httpClient = thisModule.httpClient;
    HttpRequestModel requestModel = HttpRequestModel.DEFAULT_GET;
    HttpResponseModel responseModel = HttpStreamer.getInstance().getFromUrl(url, requestModel, httpClient, null, task);
    try {
        InputStream imageStream = responseModel.stream;
        return BitmapFactory.decodeStream(imageStream);
    } finally {
        responseModel.release();
    }
}
 
Example #7
Source File: Recaptcha.java    From Overchan-Android with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Получить новую рекапчу
 * @param publicKey открытый ключ
 * @param task задача, которую можно отменить
 * @param httpClient клиент, используемый для выполнения запроса
 * @param scheme протокол (http или https), если null, по умолчанию "http"
 * @return модель рекапчи
 */
public static Recaptcha obtain(String publicKey, CancellableTask task, HttpClient httpClient, String scheme) throws RecaptchaException {
    Exception lastException = null;
    if (scheme == null) scheme = "http";
    Recaptcha recaptcha = new Recaptcha();
    for (ChallengeGetter getter : GETTERS) {
        try {
            recaptcha.challenge = getter.get(publicKey, task, httpClient, scheme);
            HttpResponseModel responseModel = null;
            try {
                responseModel = HttpStreamer.getInstance().getFromUrl(scheme + RECAPTCHA_IMAGE_URL + recaptcha.challenge,
                        HttpRequestModel.DEFAULT_GET, httpClient, null, task);
                InputStream imageStream = responseModel.stream;
                recaptcha.bitmap = BitmapFactory.decodeStream(imageStream);
            } finally {
                if (responseModel != null) responseModel.release();
            }
            if (recaptcha.bitmap != null) return recaptcha;
        } catch (Exception e) {
            lastException = e;
        }
    }
    if (lastException != null) {
        if (lastException instanceof RecaptchaException) {
            throw (RecaptchaException)lastException;
        } else {
            throw new RecaptchaException(lastException);
        }
    } else {
        throw new RecaptchaException("Can't get recaptcha");
    }
}
 
Example #8
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 #9
Source File: HttpClientWrapper.java    From Overchan-Android with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void close() throws IOException {
    HttpClient client = getClient();
    if (client instanceof Closeable) {
        ((Closeable) client).close();
    }
}
 
Example #10
Source File: FeedFragment.java    From Instagram-Profile-Downloader with MIT License 5 votes vote down vote up
@Override
protected String doInBackground(Void... params) {
    HttpClient httpClient = new DefaultHttpClient();
    HttpGet httpGet = new HttpGet(url);
    try {
        HttpResponse response = httpClient.execute(httpGet);
        HttpEntity httpEntity = response.getEntity();
        return EntityUtils.toString(httpEntity);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}
 
Example #11
Source File: ExtendedHttpClient.java    From Overchan-Android with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected HttpClient getClient() {
    if (httpClient == null) {
        synchronized (this) {
            if (httpClient == null) {
                httpClient = build(proxy, getCookieStore());
            }
        }
    }
    return httpClient;
}
 
Example #12
Source File: DownloadProfileImageActivity.java    From Instagram-Profile-Downloader with MIT License 5 votes vote down vote up
@Override
protected String doInBackground(Void... params) {
    HttpClient httpClient = new DefaultHttpClient();
    try {
        HttpGet httpGet = new HttpGet(url);
        HttpResponse response = httpClient.execute(httpGet);
        HttpEntity httpEntity = response.getEntity();
        return EntityUtils.toString(httpEntity);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}
 
Example #13
Source File: IntroScreenActivity.java    From Instagram-Profile-Downloader with MIT License 5 votes vote down vote up
@Override
protected String doInBackground(Void... params) {
    HttpClient httpClient = new DefaultHttpClient();
    HttpGet httpGet = new HttpGet(getResources().getString(R.string.get_user_info_url) + token);
    try {
        HttpResponse response = httpClient.execute(httpGet);
        HttpEntity httpEntity = response.getEntity();
        return EntityUtils.toString(httpEntity);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}
 
Example #14
Source File: MainActivity.java    From Instagram-Profile-Downloader with MIT License 5 votes vote down vote up
@Override
protected String doInBackground(Void... params) {
    HttpClient httpClient = new DefaultHttpClient();
    HttpGet httpGet = new HttpGet(final_url);
    try {
        HttpResponse response = httpClient.execute(httpGet);
        HttpEntity httpEntity = response.getEntity();
        return EntityUtils.toString(httpEntity);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}
 
Example #15
Source File: MainActivity.java    From Instagram-Profile-Downloader with MIT License 5 votes vote down vote up
@Override
protected String doInBackground(Void... params) {
    HttpClient httpClient = new DefaultHttpClient();
    HttpGet httpGet = new HttpGet(url);
    try {
        HttpResponse response = httpClient.execute(httpGet);
        HttpEntity httpEntity = response.getEntity();
        return EntityUtils.toString(httpEntity);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}
 
Example #16
Source File: OverviewDialog.java    From Instagram-Profile-Downloader with MIT License 5 votes vote down vote up
@Override
protected String doInBackground(Void... params) {
    HttpClient httpClient = new DefaultHttpClient();
    HttpGet httpGet = new HttpGet(url);
    try {
        HttpResponse response = httpClient.execute(httpGet);
        HttpEntity httpEntity = response.getEntity();
        return EntityUtils.toString(httpEntity);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}
 
Example #17
Source File: ProfileFragment.java    From Instagram-Profile-Downloader with MIT License 5 votes vote down vote up
@Override
protected String doInBackground(Void... params) {
    HttpClient httpClient = new DefaultHttpClient();
    HttpGet httpGet = new HttpGet(url);
    try {
        HttpResponse response = httpClient.execute(httpGet);
        HttpEntity httpEntity = response.getEntity();
        return EntityUtils.toString(httpEntity);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}
 
Example #18
Source File: AbstractVichanModule.java    From Overchan-Android with GNU General Public License v3.0 4 votes vote down vote up
public static List<Pair<String, String>> getFormValues(String url, CancellableTask task, HttpClient httpClient) throws Exception {
    return getFormValues(url, HttpRequestModel.DEFAULT_GET, task, httpClient, "<form name=\"post\"", "</form>");
}
 
Example #19
Source File: AbstractChanModule.java    From Overchan-Android with GNU General Public License v3.0 4 votes vote down vote up
@Override
public HttpClient getHttpClient() {
    return httpClient;
}
 
Example #20
Source File: Recaptcha.java    From Overchan-Android with GNU General Public License v3.0 4 votes vote down vote up
@Override
public String get(String publicKey, CancellableTask task, HttpClient httpClient, String scheme) throws Exception {
    return RecaptchaAjax.getChallenge(publicKey, task, httpClient, scheme);
}
 
Example #21
Source File: Recaptcha.java    From Overchan-Android with GNU General Public License v3.0 4 votes vote down vote up
@Override
public String get(String publicKey, CancellableTask task, HttpClient httpClient, String scheme) throws Exception {
    return RecaptchaNoscript.getChallenge(publicKey, task, httpClient, scheme);
}
 
Example #22
Source File: HttpStreamer.java    From Overchan-Android with GNU General Public License v3.0 3 votes vote down vote up
/**
 * HTTP запрос по адресу, получить строку
 * @param url адрес страницы
 * @param requestModel модель запроса (может принимать null, по умолчанию GET без проверки If-Modified)
 * @param httpClient HTTP клиент, исполняющий запрос
 * @param listener интерфейс отслеживания прогресса (может принимать null)
 * @param task задача, отмена которой прервёт поток (может принимать null)
 * @param anyCode загружать содержимое, даже если сервер не вернул HTTP 200, например, html страницы ошибок
 * (данные будут переданы исключению {@link HttpWrongStatusCodeException})
 * @return полученная строка, или NULL, если страница не была изменена (HTTP 304)
 * @throws IOException ошибка ввода/вывода, в т.ч. если поток прерван отменой задачи (подкласс {@link IOUtils.InterruptedStreamException})
 * @throws HttpRequestException если не удалось выполнить запрос, или содержимое отсутствует
 * @throws HttpWrongStatusCodeException если сервер вернул код не 200. При anycode==true будет содержать также HTML содержимое ответа. 
 */
public String getStringFromUrl(String url, HttpRequestModel requestModel, HttpClient httpClient, ProgressListener listener,
        CancellableTask task, boolean anyCode) throws IOException, HttpRequestException, HttpWrongStatusCodeException {
    byte[] bytes = getBytesFromUrl(url, requestModel, httpClient, listener, task, anyCode);
    if (bytes == null) return null;
    return new String(bytes);
}
 
Example #23
Source File: HttpChanModule.java    From Overchan-Android with GNU General Public License v3.0 2 votes vote down vote up
/**
 * Получить HTTP клиент, используемый данным чаном
 */
HttpClient getHttpClient();
 
Example #24
Source File: HttpStreamer.java    From Overchan-Android with GNU General Public License v3.0 2 votes vote down vote up
/**
 * HTTP запрос по адресу, получить объект JSON ({@link nya.miku.wishmaster.lib.org_json.JSONObject} актуальная версия org.json)
 * @param url адрес страницы
 * @param requestModel модель запроса (может принимать null, по умолчанию GET без проверки If-Modified)
 * @param httpClient HTTP клиент, исполняющий запрос
 * @param listener интерфейс отслеживания прогресса (может принимать null)
 * @param task задача, отмена которой прервёт поток (может принимать null)
 * @param anyCode загружать содержимое, даже если сервер не вернул HTTP 200, например, html страницы ошибок
 * (данные будут переданы исключению {@link HttpWrongStatusCodeException})
 * @return объект {@link JSONObject}, или NULL, если страница не была изменена (HTTP 304)
 * @throws IOException ошибка ввода/вывода, в т.ч. если поток прерван отменой задачи (подкласс {@link IOUtils.InterruptedStreamException})
 * @throws HttpRequestException если не удалось выполнить запрос, или содержимое отсутствует
 * @throws HttpWrongStatusCodeException если сервер вернул код не 200. При anycode==true будет содержать также HTML содержимое ответа.
 * @throws JSONException в случае ошибки при парсинге JSON
 */
public JSONObject getJSONObjectFromUrl(String url, HttpRequestModel requestModel, HttpClient httpClient, ProgressListener listener,
        CancellableTask task, boolean anyCode) throws IOException, HttpRequestException, HttpWrongStatusCodeException, JSONException {
    return (JSONObject) getJSONFromUrl(url, requestModel, httpClient, listener, task, anyCode, false);
}
 
Example #25
Source File: HttpStreamer.java    From Overchan-Android with GNU General Public License v3.0 2 votes vote down vote up
/**
 * HTTP запрос по адресу, получить массив JSON ({@link nya.miku.wishmaster.lib.org_json.JSONArray} актуальная версия org.json.JSONArray)
 * @param url адрес страницы
 * @param requestModel модель запроса (может принимать null, по умолчанию GET без проверки If-Modified)
 * @param httpClient HTTP клиент, исполняющий запрос
 * @param listener интерфейс отслеживания прогресса (может принимать null)
 * @param task задача, отмена которой прервёт поток (может принимать null)
 * @param anyCode загружать содержимое, даже если сервер не вернул HTTP 200, например, html страницы ошибок
 * (данные будут переданы исключению {@link HttpWrongStatusCodeException})
 * @return объект {@link JSONArray}, или NULL, если страница не была изменена (HTTP 304)
 * @throws IOException ошибка ввода/вывода, в т.ч. если поток прерван отменой задачи (подкласс {@link IOUtils.InterruptedStreamException})
 * @throws HttpRequestException если не удалось выполнить запрос, или содержимое отсутствует
 * @throws HttpWrongStatusCodeException если сервер вернул код не 200. При anycode==true будет содержать также HTML содержимое ответа.
 * @throws JSONException в случае ошибки при парсинге JSON
 */
public JSONArray getJSONArrayFromUrl(String url, HttpRequestModel requestModel, HttpClient httpClient, ProgressListener listener,
        CancellableTask task, boolean anyCode) throws IOException, HttpRequestException, HttpWrongStatusCodeException, JSONException {
    return (JSONArray) getJSONFromUrl(url, requestModel, httpClient, listener, task, anyCode, true);
}
 
Example #26
Source File: HttpClientWrapper.java    From Overchan-Android with GNU General Public License v3.0 votes vote down vote up
protected abstract HttpClient getClient(); 
Example #27
Source File: Recaptcha.java    From Overchan-Android with GNU General Public License v3.0 votes vote down vote up
String get(String key, CancellableTask task, HttpClient httpClient, String scheme) throws Exception;