Search in sources :

Example 26 with HttpResponse

use of org.apache.http.HttpResponse in project hive by apache.

the class HiveConnection method getHttpClient.

private CloseableHttpClient getHttpClient(Boolean useSsl) throws SQLException {
    boolean isCookieEnabled = sessConfMap.get(JdbcConnectionParams.COOKIE_AUTH) == null || (!JdbcConnectionParams.COOKIE_AUTH_FALSE.equalsIgnoreCase(sessConfMap.get(JdbcConnectionParams.COOKIE_AUTH)));
    String cookieName = sessConfMap.get(JdbcConnectionParams.COOKIE_NAME) == null ? JdbcConnectionParams.DEFAULT_COOKIE_NAMES_HS2 : sessConfMap.get(JdbcConnectionParams.COOKIE_NAME);
    CookieStore cookieStore = isCookieEnabled ? new BasicCookieStore() : null;
    HttpClientBuilder httpClientBuilder;
    // Request interceptor for any request pre-processing logic
    HttpRequestInterceptor requestInterceptor;
    Map<String, String> additionalHttpHeaders = new HashMap<String, String>();
    // Retrieve the additional HttpHeaders
    for (Map.Entry<String, String> entry : sessConfMap.entrySet()) {
        String key = entry.getKey();
        if (key.startsWith(JdbcConnectionParams.HTTP_HEADER_PREFIX)) {
            additionalHttpHeaders.put(key.substring(JdbcConnectionParams.HTTP_HEADER_PREFIX.length()), entry.getValue());
        }
    }
    // Configure http client for kerberos/password based authentication
    if (isKerberosAuthMode()) {
        /**
       * Add an interceptor which sets the appropriate header in the request.
       * It does the kerberos authentication and get the final service ticket,
       * for sending to the server before every request.
       * In https mode, the entire information is encrypted
       */
        requestInterceptor = new HttpKerberosRequestInterceptor(sessConfMap.get(JdbcConnectionParams.AUTH_PRINCIPAL), host, getServerHttpUrl(useSsl), assumeSubject, cookieStore, cookieName, useSsl, additionalHttpHeaders);
    } else {
        // Check for delegation token, if present add it in the header
        String tokenStr = getClientDelegationToken(sessConfMap);
        if (tokenStr != null) {
            requestInterceptor = new HttpTokenAuthInterceptor(tokenStr, cookieStore, cookieName, useSsl, additionalHttpHeaders);
        } else {
            /**
       * Add an interceptor to pass username/password in the header.
       * In https mode, the entire information is encrypted
       */
            requestInterceptor = new HttpBasicAuthInterceptor(getUserName(), getPassword(), cookieStore, cookieName, useSsl, additionalHttpHeaders);
        }
    }
    // Configure http client for cookie based authentication
    if (isCookieEnabled) {
        // Create a http client with a retry mechanism when the server returns a status code of 401.
        httpClientBuilder = HttpClients.custom().setServiceUnavailableRetryStrategy(new ServiceUnavailableRetryStrategy() {

            @Override
            public boolean retryRequest(final HttpResponse response, final int executionCount, final HttpContext context) {
                int statusCode = response.getStatusLine().getStatusCode();
                boolean ret = statusCode == 401 && executionCount <= 1;
                // interceptor
                if (ret) {
                    context.setAttribute(Utils.HIVE_SERVER2_RETRY_KEY, Utils.HIVE_SERVER2_RETRY_TRUE);
                }
                return ret;
            }

            @Override
            public long getRetryInterval() {
                // Immediate retry
                return 0;
            }
        });
    } else {
        httpClientBuilder = HttpClientBuilder.create();
    }
    // Add the request interceptor to the client builder
    httpClientBuilder.addInterceptorFirst(requestInterceptor);
    // Add an interceptor to add in an XSRF header
    httpClientBuilder.addInterceptorLast(new XsrfHttpRequestInterceptor());
    // Configure http client for SSL
    if (useSsl) {
        String useTwoWaySSL = sessConfMap.get(JdbcConnectionParams.USE_TWO_WAY_SSL);
        String sslTrustStorePath = sessConfMap.get(JdbcConnectionParams.SSL_TRUST_STORE);
        String sslTrustStorePassword = sessConfMap.get(JdbcConnectionParams.SSL_TRUST_STORE_PASSWORD);
        KeyStore sslTrustStore;
        SSLConnectionSocketFactory socketFactory;
        SSLContext sslContext;
        /**
       * The code within the try block throws: SSLInitializationException, KeyStoreException,
       * IOException, NoSuchAlgorithmException, CertificateException, KeyManagementException &
       * UnrecoverableKeyException. We don't want the client to retry on any of these,
       * hence we catch all and throw a SQLException.
       */
        try {
            if (useTwoWaySSL != null && useTwoWaySSL.equalsIgnoreCase(JdbcConnectionParams.TRUE)) {
                socketFactory = getTwoWaySSLSocketFactory();
            } else if (sslTrustStorePath == null || sslTrustStorePath.isEmpty()) {
                // Create a default socket factory based on standard JSSE trust material
                socketFactory = SSLConnectionSocketFactory.getSocketFactory();
            } else {
                // Pick trust store config from the given path
                sslTrustStore = KeyStore.getInstance(JdbcConnectionParams.SSL_TRUST_STORE_TYPE);
                try (FileInputStream fis = new FileInputStream(sslTrustStorePath)) {
                    sslTrustStore.load(fis, sslTrustStorePassword.toCharArray());
                }
                sslContext = SSLContexts.custom().loadTrustMaterial(sslTrustStore, null).build();
                socketFactory = new SSLConnectionSocketFactory(sslContext, new DefaultHostnameVerifier(null));
            }
            final Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create().register("https", socketFactory).build();
            httpClientBuilder.setConnectionManager(new BasicHttpClientConnectionManager(registry));
        } catch (Exception e) {
            String msg = "Could not create an https connection to " + jdbcUriString + ". " + e.getMessage();
            throw new SQLException(msg, " 08S01", e);
        }
    }
    return httpClientBuilder.build();
}
Also used : HashMap(java.util.HashMap) SQLException(java.sql.SQLException) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) ServiceUnavailableRetryStrategy(org.apache.http.client.ServiceUnavailableRetryStrategy) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) ConnectionSocketFactory(org.apache.http.conn.socket.ConnectionSocketFactory) DefaultHostnameVerifier(org.apache.http.conn.ssl.DefaultHostnameVerifier) BasicHttpClientConnectionManager(org.apache.http.impl.conn.BasicHttpClientConnectionManager) HttpContext(org.apache.http.protocol.HttpContext) HttpResponse(org.apache.http.HttpResponse) SSLContext(javax.net.ssl.SSLContext) KeyStore(java.security.KeyStore) Savepoint(java.sql.Savepoint) FileInputStream(java.io.FileInputStream) TTransportException(org.apache.thrift.transport.TTransportException) SQLFeatureNotSupportedException(java.sql.SQLFeatureNotSupportedException) SaslException(javax.security.sasl.SaslException) InvocationTargetException(java.lang.reflect.InvocationTargetException) SQLClientInfoException(java.sql.SQLClientInfoException) SQLException(java.sql.SQLException) TException(org.apache.thrift.TException) IOException(java.io.IOException) CookieStore(org.apache.http.client.CookieStore) BasicCookieStore(org.apache.http.impl.client.BasicCookieStore) BasicCookieStore(org.apache.http.impl.client.BasicCookieStore) HttpRequestInterceptor(org.apache.http.HttpRequestInterceptor) Map(java.util.Map) HashMap(java.util.HashMap)

Example 27 with HttpResponse

use of org.apache.http.HttpResponse in project coinbase-bitmonet-sdk by coinbase.

the class CoinbasePaymentProcessor method transferMoney.

@Override
public void transferMoney(final Context context, final String item, final double amount) {
    new Thread(new Runnable() {

        @Override
        public void run() {
            try {
                // token
                if (OAuthHelperUtils.getInstance().shouldRequestNewAccessToken()) {
                    OAuthHelperUtils.getInstance().refreshAccessToken();
                }
                String path = URLUtils.constructSendMoneyURL();
                String json = constructJSONForSendMoney(item, amount);
                HttpResponse response = HTTPUtils.makeHttpPostWithJSONRequest(path, json);
                processResponse(context, response);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }).start();
}
Also used : HttpResponse(org.apache.http.HttpResponse) JSONException(org.json.JSONException) IOException(java.io.IOException)

Example 28 with HttpResponse

use of org.apache.http.HttpResponse in project coinbase-bitmonet-sdk by coinbase.

the class OAuthHelperUtils method requestAccesTokenFromCoinbase.

public void requestAccesTokenFromCoinbase(final Context context, final String code) {
    if (code == null) {
        return;
    }
    new Thread(new Runnable() {

        @Override
        public void run() {
            String path = URLUtils.constructAuthRequestTokenURL(code);
            HttpResponse response = HTTPUtils.makeHttpPostRequest(path);
            if (response != null && response.getStatusLine().getStatusCode() == 200) {
                try {
                    extractOAuthParamatersFromJSON(response);
                    UserProfileSettings.getInstance().saveCoinbaseOAuthStatus(true);
                    UserProfileSettings.getInstance().saveCoinbaseAccessTokenTimestamp(System.currentTimeMillis());
                    sendOAuthResponse(context, true);
                    return;
                } catch (JSONException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            sendOAuthResponse(context, false);
            UserProfileSettings.getInstance().saveCoinbaseOAuthStatus(false);
        }
    }).start();
}
Also used : HttpResponse(org.apache.http.HttpResponse) JSONException(org.json.JSONException) IOException(java.io.IOException)

Example 29 with HttpResponse

use of org.apache.http.HttpResponse in project SimplifyReader by chentao0707.

the class BasicNetwork method performRequest.

@Override
public NetworkResponse performRequest(Request<?> request) throws VolleyError {
    long requestStart = SystemClock.elapsedRealtime();
    while (true) {
        HttpResponse httpResponse = null;
        byte[] responseContents = null;
        Map<String, String> responseHeaders = Collections.emptyMap();
        try {
            // Gather headers.
            Map<String, String> headers = new HashMap<String, String>();
            addCacheHeaders(headers, request.getCacheEntry());
            httpResponse = mHttpStack.performRequest(request, headers);
            StatusLine statusLine = httpResponse.getStatusLine();
            int statusCode = statusLine.getStatusCode();
            responseHeaders = convertHeaders(httpResponse.getAllHeaders());
            // Handle cache validation.
            if (statusCode == HttpStatus.SC_NOT_MODIFIED) {
                Entry entry = request.getCacheEntry();
                if (entry == null) {
                    return new NetworkResponse(HttpStatus.SC_NOT_MODIFIED, null, responseHeaders, true, SystemClock.elapsedRealtime() - requestStart);
                }
                // A HTTP 304 response does not have all header fields. We
                // have to use the header fields from the cache entry plus
                // the new ones from the response.
                // http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.5
                entry.responseHeaders.putAll(responseHeaders);
                return new NetworkResponse(HttpStatus.SC_NOT_MODIFIED, entry.data, entry.responseHeaders, true, SystemClock.elapsedRealtime() - requestStart);
            }
            // Some responses such as 204s do not have content.  We must check.
            if (httpResponse.getEntity() != null) {
                responseContents = entityToBytes(httpResponse.getEntity());
            } else {
                // Add 0 byte response as a way of honestly representing a
                // no-content request.
                responseContents = new byte[0];
            }
            // if the request is slow, log it.
            long requestLifetime = SystemClock.elapsedRealtime() - requestStart;
            logSlowRequests(requestLifetime, request, responseContents, statusLine);
            if (statusCode < 200 || statusCode > 299) {
                throw new IOException();
            }
            return new NetworkResponse(statusCode, responseContents, responseHeaders, false, SystemClock.elapsedRealtime() - requestStart);
        } catch (SocketTimeoutException e) {
            attemptRetryOnException("socket", request, new TimeoutError());
        } catch (ConnectTimeoutException e) {
            attemptRetryOnException("connection", request, new TimeoutError());
        } catch (MalformedURLException e) {
            throw new RuntimeException("Bad URL " + request.getUrl(), e);
        } catch (IOException e) {
            int statusCode = 0;
            NetworkResponse networkResponse = null;
            if (httpResponse != null) {
                statusCode = httpResponse.getStatusLine().getStatusCode();
            } else {
                throw new NoConnectionError(e);
            }
            VolleyLog.e("Unexpected response code %d for %s", statusCode, request.getUrl());
            if (responseContents != null) {
                networkResponse = new NetworkResponse(statusCode, responseContents, responseHeaders, false, SystemClock.elapsedRealtime() - requestStart);
                if (statusCode == HttpStatus.SC_UNAUTHORIZED || statusCode == HttpStatus.SC_FORBIDDEN) {
                    attemptRetryOnException("auth", request, new AuthFailureError(networkResponse));
                } else {
                    // TODO: Only throw ServerError for 5xx status codes.
                    throw new ServerError(networkResponse);
                }
            } else {
                throw new NetworkError(networkResponse);
            }
        }
    }
}
Also used : MalformedURLException(java.net.MalformedURLException) HashMap(java.util.HashMap) ServerError(com.android.volley.ServerError) HttpResponse(org.apache.http.HttpResponse) AuthFailureError(com.android.volley.AuthFailureError) NetworkError(com.android.volley.NetworkError) NoConnectionError(com.android.volley.NoConnectionError) IOException(java.io.IOException) TimeoutError(com.android.volley.TimeoutError) StatusLine(org.apache.http.StatusLine) Entry(com.android.volley.Cache.Entry) SocketTimeoutException(java.net.SocketTimeoutException) NetworkResponse(com.android.volley.NetworkResponse) ConnectTimeoutException(org.apache.http.conn.ConnectTimeoutException)

Example 30 with HttpResponse

use of org.apache.http.HttpResponse in project PlayerHater by chrisrhoden.

the class PlaylistParser method parsePls.

private static Uri[] parsePls(Uri uri) {
    try {
        HttpClient httpclient = new DefaultHttpClient();
        HttpResponse response = httpclient.execute(new HttpGet(uri.toString()));
        HttpEntity entity = response.getEntity();
        InputStream inputStream = entity.getContent();
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
        String header = reader.readLine();
        if (header.trim().equalsIgnoreCase("[playlist]")) {
            String line;
            ArrayList<Uri> uriList = new ArrayList<Uri>();
            do {
                line = reader.readLine();
                if (line != null) {
                    if (line.startsWith("File")) {
                        String fileName = line.substring(line.indexOf("=") + 1).trim();
                        uriList.add(Uri.parse(fileName));
                    }
                }
            } while (line != null);
            if (uriList.size() > 0) {
                Uri[] res = new Uri[uriList.size()];
                return uriList.toArray(res);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return new Uri[] { uri };
}
Also used : HttpEntity(org.apache.http.HttpEntity) InputStreamReader(java.io.InputStreamReader) InputStream(java.io.InputStream) HttpGet(org.apache.http.client.methods.HttpGet) ArrayList(java.util.ArrayList) HttpResponse(org.apache.http.HttpResponse) Uri(android.net.Uri) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) HttpClient(org.apache.http.client.HttpClient) BufferedReader(java.io.BufferedReader)

Aggregations

HttpResponse (org.apache.http.HttpResponse)1502 HttpGet (org.apache.http.client.methods.HttpGet)717 Test (org.junit.Test)686 IOException (java.io.IOException)355 TestHttpClient (io.undertow.testutils.TestHttpClient)290 HttpPost (org.apache.http.client.methods.HttpPost)238 HttpClient (org.apache.http.client.HttpClient)237 DefaultHttpClient (org.apache.http.impl.client.DefaultHttpClient)219 HttpEntity (org.apache.http.HttpEntity)192 Header (org.apache.http.Header)178 StringEntity (org.apache.http.entity.StringEntity)138 ArrayList (java.util.ArrayList)104 CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)104 InputStream (java.io.InputStream)97 BasicNameValuePair (org.apache.http.message.BasicNameValuePair)81 URI (java.net.URI)77 StatusLine (org.apache.http.StatusLine)76 ClientProtocolException (org.apache.http.client.ClientProtocolException)76 UrlEncodedFormEntity (org.apache.http.client.entity.UrlEncodedFormEntity)71 NameValuePair (org.apache.http.NameValuePair)63