Search in sources :

Example 6 with HttpUriRequestBase

use of org.apache.hc.client5.http.classic.methods.HttpUriRequestBase in project ajapaik-android-app by Ajapaik.

the class WebOperation method performRequest.

public boolean performRequest(String baseURL, Map<String, String> extraParameters, BasicCookieStore cookieStore) {
    Log.d(TAG, "performRequest()");
    ConnectivityManager cm = (ConnectivityManager) m_context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo info = cm.getActiveNetworkInfo();
    boolean isPost = isPost();
    String url = m_url;
    URI uri;
    if (baseURL != null && !url.contains("://")) {
        if (url.startsWith("/") && baseURL.endsWith("/")) {
            url = baseURL + url.substring(1);
        } else {
            url = baseURL + url;
        }
    }
    if (m_client == null) {
        if (BuildConfig.DEBUG) {
            Log.d(TAG, "new m_client");
        }
        try {
            m_client = HttpClients.custom().setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy()).setDefaultCookieStore(cookieStore).build();
        } catch (Exception e) {
            Log.w(TAG, e.toString());
        }
    }
    if (BuildConfig.DEBUG) {
        Log.d(TAG, "m_client ready");
    }
    m_started = true;
    if (info == null || info.getState() == NetworkInfo.State.DISCONNECTED) {
        onFailure();
        if (BuildConfig.DEBUG) {
            Log.d(TAG, "No network connection");
        }
        return false;
    }
    try {
        uri = URI.create(url);
    } catch (Exception e) {
        Log.w(TAG, "Unable to parse URL (" + url + ")");
        onFailure();
        return false;
    }
    for (int i = 0; i < RETRY_COUNT && !m_cancelled; i++) {
        CloseableHttpResponse response = null;
        HttpUriRequestBase request;
        if (isPost) {
            HttpPost postRequest = new HttpPost(uri);
            request = postRequest;
            if (m_file != null || (extraParameters != null && extraParameters.size() > 0) || (m_parameters != null && m_parameters.size() > 0)) {
                List<NameValuePair> postData = new ArrayList<NameValuePair>(((extraParameters != null) ? extraParameters.size() : 0) + ((m_parameters != null) ? m_parameters.size() : 0));
                if (m_parameters != null) {
                    for (Map.Entry<String, String> entry : m_parameters.entrySet()) {
                        postData.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
                    }
                }
                if (extraParameters != null) {
                    for (Map.Entry<String, String> entry : extraParameters.entrySet()) {
                        postData.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
                    }
                }
                try {
                    StringBuilder strData = new StringBuilder();
                    String separator = "";
                    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
                    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
                    if (m_file != null) {
                        Log.d(TAG, "Adding file to post");
                        for (NameValuePair pair : postData) {
                            StringBody stringBody1 = new StringBody(pair.getValue(), ContentType.MULTIPART_FORM_DATA);
                            builder.addPart(pair.getName(), stringBody1);
                            strData.append(separator);
                            strData.append(pair.toString());
                            separator = "&";
                        }
                        FileBody fileBody = new FileBody(m_file, ContentType.DEFAULT_BINARY);
                        builder.addPart("original", fileBody);
                        HttpEntity entity = builder.build();
                        postRequest.setEntity(entity);
                    } else {
                        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(postData);
                        postRequest.setEntity(entity);
                        for (NameValuePair pair : postData) {
                            strData.append(separator);
                            strData.append(pair.toString());
                            separator = "&";
                        }
                    }
                    if (BuildConfig.DEBUG) {
                        Log.d(TAG, strData.toString());
                    }
                } catch (Exception e) {
                    Log.d(TAG, "UTF8 is not supported");
                }
            }
        } else if ((extraParameters != null && extraParameters.size() > 0) || (m_parameters != null && m_parameters.size() > 0)) {
            Uri.Builder uriBuilder = Uri.parse(m_url).buildUpon();
            if (m_parameters != null) {
                for (Map.Entry<String, String> entry : m_parameters.entrySet()) {
                    uriBuilder.appendQueryParameter(entry.getKey(), entry.getValue());
                }
            }
            if (extraParameters != null) {
                for (Map.Entry<String, String> entry : extraParameters.entrySet()) {
                    uriBuilder.appendQueryParameter(entry.getKey(), entry.getValue());
                }
            }
            request = new HttpGet(URI.create(uriBuilder.build().toString()));
        } else {
            request = new HttpGet(uri);
        }
        request.setHeader("Accept-Encoding", CONTENT_ENCODING_GZIP);
        try {
            String encoding = null;
            HttpEntity entity;
            if (BuildConfig.DEBUG) {
                Log.e(TAG, "Retry count:" + i);
                Log.e(TAG, ((isPost) ? "POST: " : "GET: ") + request.toString());
                Log.e(TAG, "Cookies before: " + cookieStore.getCookies().toString());
            }
            response = m_client.execute(request);
            if ((entity = response.getEntity()) != null) {
                encoding = entity.getContentEncoding();
            }
            try {
                onResponse(response.getCode(), (encoding != null && CONTENT_ENCODING_GZIP.equals(encoding)) ? new GZIPInputStream(entity.getContent()) : entity.getContent());
                Log.e(TAG, "responseCode: " + response.getCode());
                Log.e(TAG, "Cookies after: " + cookieStore.getCookies().toString());
                List<Cookie> cookies = cookieStore.getCookies();
                String session_id = null;
                for (int n = 0; n < cookies.size(); n++) {
                    if (cookies.get(n).getName().equals("sessionid")) {
                        Log.d(TAG, "Cookie :" + cookies.get(n).getName() + "; value " + cookies.get(n).getValue());
                        session_id = cookies.get(n).getValue();
                    }
                }
                // If no session_id in response then kill login
                if (session_id == null) {
                    Log.e(TAG, "No session_id in response cookie");
                    m_settings.setSession(null);
                }
            } catch (ApiException e) {
                Crashlytics.log(e.toString());
                Crashlytics.setString("URL", url);
                if (m_parameters != null && !m_parameters.isEmpty()) {
                    Crashlytics.setString("params", new JSONObject(m_parameters).toString());
                }
                Crashlytics.logException(e);
            }
            response.close();
            return true;
        } catch (IOException e) {
            if (BuildConfig.DEBUG) {
                Log.w(TAG, "Network error", e);
            }
            Crashlytics.log(e.toString());
            Crashlytics.setString("URL", url);
            Crashlytics.logException(e);
            try {
                HttpEntity entity = response.getEntity();
                entity.getContent().close();
            } catch (Exception e1) {
            }
            request.abort();
            try {
                Thread.sleep(RETRY_INTERVAL);
            } catch (InterruptedException e1) {
            }
        }
    }
    return true;
}
Also used : HttpPost(org.apache.hc.client5.http.classic.methods.HttpPost) MultipartEntityBuilder(org.apache.hc.client5.http.entity.mime.MultipartEntityBuilder) HttpEntity(org.apache.hc.core5.http.HttpEntity) ConnectivityManager(android.net.ConnectivityManager) MultipartEntityBuilder(org.apache.hc.client5.http.entity.mime.MultipartEntityBuilder) HttpGet(org.apache.hc.client5.http.classic.methods.HttpGet) ArrayList(java.util.ArrayList) URI(java.net.URI) GZIPInputStream(java.util.zip.GZIPInputStream) DefaultConnectionKeepAliveStrategy(org.apache.hc.client5.http.impl.DefaultConnectionKeepAliveStrategy) BasicNameValuePair(org.apache.hc.core5.http.message.BasicNameValuePair) CloseableHttpResponse(org.apache.hc.client5.http.impl.classic.CloseableHttpResponse) Cookie(org.apache.hc.client5.http.cookie.Cookie) BasicNameValuePair(org.apache.hc.core5.http.message.BasicNameValuePair) NameValuePair(org.apache.hc.core5.http.NameValuePair) HttpUriRequestBase(org.apache.hc.client5.http.classic.methods.HttpUriRequestBase) FileBody(org.apache.hc.client5.http.entity.mime.FileBody) NetworkInfo(android.net.NetworkInfo) UrlEncodedFormEntity(org.apache.hc.client5.http.entity.UrlEncodedFormEntity) IOException(java.io.IOException) IOException(java.io.IOException) ApiException(ee.ajapaik.android.exception.ApiException) JSONObject(org.json.JSONObject) StringBody(org.apache.hc.client5.http.entity.mime.StringBody) Map(java.util.Map) ApiException(ee.ajapaik.android.exception.ApiException)

Example 7 with HttpUriRequestBase

use of org.apache.hc.client5.http.classic.methods.HttpUriRequestBase in project webdrivermanager by bonigarcia.

the class ServerResolverTest method testServerResolver.

@ParameterizedTest
@MethodSource("data")
void testServerResolver(String path, String driver) throws IOException {
    String serverUrl = String.format("http://localhost:%s/%s", serverPort, path);
    try (CloseableHttpClient client = HttpClientBuilder.create().build()) {
        HttpUriRequestBase request = new HttpGet(serverUrl);
        // Assert response
        log.debug("Request: GET {}", serverUrl);
        try (CloseableHttpResponse response = client.execute(request)) {
            int responseCode = response.getCode();
            log.debug("Response: {}", responseCode);
            assertThat(responseCode).isEqualTo(200);
            // Assert attachment
            String attachment = String.format("attachment; filename=\"%s\"", driver);
            List<Header> headerList = Arrays.asList(response.getHeaders());
            List<Header> collect = headerList.stream().filter(x -> x.toString().contains("Content-Disposition")).collect(toList());
            log.debug("Assessing {} ... headers should contain {}", driver, attachment);
            assertThat(collect.get(0)).toString().contains(attachment);
        }
    }
}
Also used : PortProber.findFreePort(org.openqa.selenium.net.PortProber.findFreePort) Arrays(java.util.Arrays) HttpClientBuilder(org.apache.hc.client5.http.impl.classic.HttpClientBuilder) HttpUriRequestBase(org.apache.hc.client5.http.classic.methods.HttpUriRequestBase) Logger(org.slf4j.Logger) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) Header(org.apache.hc.core5.http.Header) IOException(java.io.IOException) HttpGet(org.apache.hc.client5.http.classic.methods.HttpGet) Arguments(org.junit.jupiter.params.provider.Arguments) MethodHandles.lookup(java.lang.invoke.MethodHandles.lookup) WebDriverManager(io.github.bonigarcia.wdm.WebDriverManager) Collectors.toList(java.util.stream.Collectors.toList) List(java.util.List) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) Stream(java.util.stream.Stream) BeforeAll(org.junit.jupiter.api.BeforeAll) IS_OS_WINDOWS(org.apache.commons.lang3.SystemUtils.IS_OS_WINDOWS) LoggerFactory.getLogger(org.slf4j.LoggerFactory.getLogger) CloseableHttpResponse(org.apache.hc.client5.http.impl.classic.CloseableHttpResponse) CloseableHttpClient(org.apache.hc.client5.http.impl.classic.CloseableHttpClient) MethodSource(org.junit.jupiter.params.provider.MethodSource) CloseableHttpClient(org.apache.hc.client5.http.impl.classic.CloseableHttpClient) HttpUriRequestBase(org.apache.hc.client5.http.classic.methods.HttpUriRequestBase) Header(org.apache.hc.core5.http.Header) HttpGet(org.apache.hc.client5.http.classic.methods.HttpGet) CloseableHttpResponse(org.apache.hc.client5.http.impl.classic.CloseableHttpResponse) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) MethodSource(org.junit.jupiter.params.provider.MethodSource)

Example 8 with HttpUriRequestBase

use of org.apache.hc.client5.http.classic.methods.HttpUriRequestBase in project invesdwin-util by invesdwin.

the class URIsConnectApacheSync method openConnection.

public CloseableHttpResponse openConnection(final String method) throws IOException {
    final HttpUriRequestBase request = (HttpUriRequestBase) ClassicHttpRequests.create(method, uri);
    request.setConfig(getRequestConfig());
    if (headers != null) {
        for (final Entry<String, String> header : headers.entrySet()) {
            request.addHeader(header.getKey(), header.getValue());
        }
    }
    if (body != null) {
        final ContentType commonsContentType;
        if (contentType != null) {
            commonsContentType = ContentType.create(contentType);
        } else {
            commonsContentType = null;
        }
        request.setEntity(new ByteArrayEntity(body, commonsContentType));
    }
    final CloseableHttpResponse response = getHttpClient().execute(request);
    return response;
}
Also used : HttpUriRequestBase(org.apache.hc.client5.http.classic.methods.HttpUriRequestBase) ContentType(org.apache.hc.core5.http.ContentType) ByteArrayEntity(org.apache.hc.core5.http.io.entity.ByteArrayEntity) CloseableHttpResponse(org.apache.hc.client5.http.impl.classic.CloseableHttpResponse)

Example 9 with HttpUriRequestBase

use of org.apache.hc.client5.http.classic.methods.HttpUriRequestBase in project adyen-java-api-library by Adyen.

the class AdyenHttpClient method createRequest.

private HttpUriRequestBase createRequest(String endpoint, String requestBody, Config config, boolean isApiKeyRequired, RequestOptions requestOptions, ApiConstants.HttpMethod httpMethod, Map<String, String> params) throws HTTPClientException {
    HttpUriRequestBase httpRequest = createHttpRequestBase(createUri(endpoint, params), requestBody, httpMethod);
    RequestConfig.Builder builder = RequestConfig.custom();
    if (config.getReadTimeoutMillis() > 0) {
        builder.setResponseTimeout(config.getReadTimeoutMillis(), TimeUnit.MILLISECONDS);
    }
    if (config.getConnectionTimeoutMillis() > 0) {
        builder.setConnectTimeout(config.getConnectionTimeoutMillis(), TimeUnit.MILLISECONDS);
    }
    if (proxy != null && proxy.address() instanceof InetSocketAddress) {
        InetSocketAddress inetSocketAddress = (InetSocketAddress) proxy.address();
        builder.setProxy(new HttpHost(inetSocketAddress.getHostName(), inetSocketAddress.getPort()));
    }
    httpRequest.setConfig(builder.build());
    setAuthentication(httpRequest, isApiKeyRequired, config);
    setHeaders(config, requestOptions, httpRequest);
    return httpRequest;
}
Also used : RequestConfig(org.apache.hc.client5.http.config.RequestConfig) HttpUriRequestBase(org.apache.hc.client5.http.classic.methods.HttpUriRequestBase) InetSocketAddress(java.net.InetSocketAddress) HttpHost(org.apache.hc.core5.http.HttpHost)

Aggregations

HttpUriRequestBase (org.apache.hc.client5.http.classic.methods.HttpUriRequestBase)8 CloseableHttpResponse (org.apache.hc.client5.http.impl.classic.CloseableHttpResponse)5 HttpGet (org.apache.hc.client5.http.classic.methods.HttpGet)4 CloseableHttpClient (org.apache.hc.client5.http.impl.classic.CloseableHttpClient)4 IOException (java.io.IOException)3 HttpPost (org.apache.hc.client5.http.classic.methods.HttpPost)3 RequestConfig (org.apache.hc.client5.http.config.RequestConfig)3 HttpEntity (org.apache.hc.core5.http.HttpEntity)3 StringEntity (org.apache.hc.core5.http.io.entity.StringEntity)3 URI (java.net.URI)2 HttpDelete (org.apache.hc.client5.http.classic.methods.HttpDelete)2 ConnectivityManager (android.net.ConnectivityManager)1 NetworkInfo (android.net.NetworkInfo)1 ApiException (ee.ajapaik.android.exception.ApiException)1 WebDriverManager (io.github.bonigarcia.wdm.WebDriverManager)1 MethodHandles.lookup (java.lang.invoke.MethodHandles.lookup)1 InetSocketAddress (java.net.InetSocketAddress)1 URISyntaxException (java.net.URISyntaxException)1 ArrayList (java.util.ArrayList)1 Arrays (java.util.Arrays)1