Search in sources :

Example 31 with HttpRequest

use of org.apache.http.HttpRequest in project spring-cloud-netflix by spring-cloud.

the class GZIPCompression method redirectTest.

@Test
public void redirectTest() throws Exception {
    setupContext();
    InputStreamEntity inputStreamEntity = new InputStreamEntity(new ByteArrayInputStream(new byte[] {}));
    HttpRequest httpRequest = getFilter().buildHttpRequest("GET", "/app/redirect", inputStreamEntity, new LinkedMultiValueMap<String, String>(), new LinkedMultiValueMap<String, String>(), new MockHttpServletRequest());
    CloseableHttpResponse response = getFilter().newClient().execute(new HttpHost("localhost", this.port), httpRequest);
    assertEquals(302, response.getStatusLine().getStatusCode());
    String responseString = copyToString(response.getEntity().getContent(), Charset.forName("UTF-8"));
    assertTrue(response.getLastHeader("Location").getValue().contains("/app/get/5"));
}
Also used : HttpRequest(org.apache.http.HttpRequest) ByteArrayInputStream(java.io.ByteArrayInputStream) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) HttpHost(org.apache.http.HttpHost) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) StreamUtils.copyToString(org.springframework.util.StreamUtils.copyToString) InputStreamEntity(org.apache.http.entity.InputStreamEntity) SpringBootTest(org.springframework.boot.test.context.SpringBootTest) Test(org.junit.Test)

Example 32 with HttpRequest

use of org.apache.http.HttpRequest in project spring-cloud-netflix by spring-cloud.

the class GZIPCompression method pathRequestBuiltWithBody.

@Test
public void pathRequestBuiltWithBody() throws Exception {
    setupContext();
    InputStreamEntity inputStreamEntity = new InputStreamEntity(new ByteArrayInputStream(new byte[] { 1 }));
    HttpRequest httpRequest = getFilter().buildHttpRequest("PATCH", "uri", inputStreamEntity, new LinkedMultiValueMap<String, String>(), new LinkedMultiValueMap<String, String>(), new MockHttpServletRequest());
    HttpPatch basicHttpRequest = (HttpPatch) httpRequest;
    assertTrue(basicHttpRequest.getEntity() != null);
}
Also used : HttpRequest(org.apache.http.HttpRequest) ByteArrayInputStream(java.io.ByteArrayInputStream) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) StreamUtils.copyToString(org.springframework.util.StreamUtils.copyToString) HttpPatch(org.apache.http.client.methods.HttpPatch) InputStreamEntity(org.apache.http.entity.InputStreamEntity) SpringBootTest(org.springframework.boot.test.context.SpringBootTest) Test(org.junit.Test)

Example 33 with HttpRequest

use of org.apache.http.HttpRequest in project spring-cloud-netflix by spring-cloud.

the class SimpleHostRoutingFilter method buildHttpRequest.

protected HttpRequest buildHttpRequest(String verb, String uri, InputStreamEntity entity, MultiValueMap<String, String> headers, MultiValueMap<String, String> params, HttpServletRequest request) {
    HttpRequest httpRequest;
    String uriWithQueryString = uri + (this.forceOriginalQueryStringEncoding ? getEncodedQueryString(request) : this.helper.getQueryString(params));
    switch(verb.toUpperCase()) {
        case "POST":
            HttpPost httpPost = new HttpPost(uriWithQueryString);
            httpRequest = httpPost;
            httpPost.setEntity(entity);
            break;
        case "PUT":
            HttpPut httpPut = new HttpPut(uriWithQueryString);
            httpRequest = httpPut;
            httpPut.setEntity(entity);
            break;
        case "PATCH":
            HttpPatch httpPatch = new HttpPatch(uriWithQueryString);
            httpRequest = httpPatch;
            httpPatch.setEntity(entity);
            break;
        case "DELETE":
            BasicHttpEntityEnclosingRequest entityRequest = new BasicHttpEntityEnclosingRequest(verb, uriWithQueryString);
            httpRequest = entityRequest;
            entityRequest.setEntity(entity);
            break;
        default:
            httpRequest = new BasicHttpRequest(verb, uriWithQueryString);
            log.debug(uriWithQueryString);
    }
    httpRequest.setHeaders(convertHeaders(headers));
    return httpRequest;
}
Also used : BasicHttpRequest(org.apache.http.message.BasicHttpRequest) HttpRequest(org.apache.http.HttpRequest) HttpPost(org.apache.http.client.methods.HttpPost) HttpPut(org.apache.http.client.methods.HttpPut) HttpPatch(org.apache.http.client.methods.HttpPatch) BasicHttpRequest(org.apache.http.message.BasicHttpRequest) BasicHttpEntityEnclosingRequest(org.apache.http.message.BasicHttpEntityEnclosingRequest)

Example 34 with HttpRequest

use of org.apache.http.HttpRequest in project spring-cloud-netflix by spring-cloud.

the class SimpleHostRoutingFilter method forward.

private CloseableHttpResponse forward(CloseableHttpClient httpclient, String verb, String uri, HttpServletRequest request, MultiValueMap<String, String> headers, MultiValueMap<String, String> params, InputStream requestEntity) throws Exception {
    Map<String, Object> info = this.helper.debug(verb, uri, headers, params, requestEntity);
    URL host = RequestContext.getCurrentContext().getRouteHost();
    HttpHost httpHost = getHttpHost(host);
    uri = StringUtils.cleanPath((host.getPath() + uri).replaceAll("/{2,}", "/"));
    int contentLength = request.getContentLength();
    ContentType contentType = null;
    if (request.getContentType() != null) {
        contentType = ContentType.parse(request.getContentType());
    }
    InputStreamEntity entity = new InputStreamEntity(requestEntity, contentLength, contentType);
    HttpRequest httpRequest = buildHttpRequest(verb, uri, entity, headers, params, request);
    try {
        log.debug(httpHost.getHostName() + " " + httpHost.getPort() + " " + httpHost.getSchemeName());
        CloseableHttpResponse zuulResponse = forwardRequest(httpclient, httpHost, httpRequest);
        this.helper.appendDebug(info, zuulResponse.getStatusLine().getStatusCode(), revertHeaders(zuulResponse.getAllHeaders()));
        return zuulResponse;
    } finally {
    // When HttpClient instance is no longer needed,
    // shut down the connection manager to ensure
    // immediate deallocation of all system resources
    // httpclient.getConnectionManager().shutdown();
    }
}
Also used : BasicHttpRequest(org.apache.http.message.BasicHttpRequest) HttpRequest(org.apache.http.HttpRequest) ContentType(org.apache.http.entity.ContentType) HttpHost(org.apache.http.HttpHost) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) URL(java.net.URL) InputStreamEntity(org.apache.http.entity.InputStreamEntity)

Example 35 with HttpRequest

use of org.apache.http.HttpRequest in project android-aosp-mms by slvn.

the class HttpUtils method httpConnection.

/**
 * A helper method to send or retrieve data through HTTP protocol.
 *
 * @param token The token to identify the sending progress.
 * @param url The URL used in a GET request. Null when the method is
 *         HTTP_POST_METHOD.
 * @param pdu The data to be POST. Null when the method is HTTP_GET_METHOD.
 * @param method HTTP_POST_METHOD or HTTP_GET_METHOD.
 * @return A byte array which contains the response data.
 *         If an HTTP error code is returned, an IOException will be thrown.
 * @throws IOException if any error occurred on network interface or
 *         an HTTP error code(&gt;=400) returned from the server.
 */
protected static byte[] httpConnection(Context context, long token, String url, byte[] pdu, int method, boolean isProxySet, String proxyHost, int proxyPort) throws IOException {
    if (url == null) {
        throw new IllegalArgumentException("URL must not be null.");
    }
    if (Log.isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) {
        Log.v(TAG, "httpConnection: params list");
        Log.v(TAG, "\ttoken\t\t= " + token);
        Log.v(TAG, "\turl\t\t= " + url);
        Log.v(TAG, "\tmethod\t\t= " + ((method == HTTP_POST_METHOD) ? "POST" : ((method == HTTP_GET_METHOD) ? "GET" : "UNKNOWN")));
        Log.v(TAG, "\tisProxySet\t= " + isProxySet);
        Log.v(TAG, "\tproxyHost\t= " + proxyHost);
        Log.v(TAG, "\tproxyPort\t= " + proxyPort);
    // TODO Print out binary data more readable.
    // Log.v(TAG, "\tpdu\t\t= " + Arrays.toString(pdu));
    }
    AndroidHttpClient client = null;
    try {
        // Make sure to use a proxy which supports CONNECT.
        URI hostUrl = new URI(url);
        HttpHost target = new HttpHost(hostUrl.getHost(), hostUrl.getPort(), HttpHost.DEFAULT_SCHEME_NAME);
        client = createHttpClient(context);
        HttpRequest req = null;
        switch(method) {
            case HTTP_POST_METHOD:
                ProgressCallbackEntity entity = new ProgressCallbackEntity(context, token, pdu);
                // Set request content type.
                entity.setContentType("application/vnd.wap.mms-message");
                HttpPost post = new HttpPost(url);
                post.setEntity(entity);
                req = post;
                break;
            case HTTP_GET_METHOD:
                req = new HttpGet(url);
                break;
            default:
                Log.e(TAG, "Unknown HTTP method: " + method + ". Must be one of POST[" + HTTP_POST_METHOD + "] or GET[" + HTTP_GET_METHOD + "].");
                return null;
        }
        // Set route parameters for the request.
        HttpParams params = client.getParams();
        if (isProxySet) {
            ConnRouteParams.setDefaultProxy(params, new HttpHost(proxyHost, proxyPort));
        }
        req.setParams(params);
        // Set necessary HTTP headers for MMS transmission.
        req.addHeader(HDR_KEY_ACCEPT, HDR_VALUE_ACCEPT);
        {
            String xWapProfileTagName = MmsConfig.getUaProfTagName();
            String xWapProfileUrl = MmsConfig.getUaProfUrl();
            if (xWapProfileUrl != null) {
                if (Log.isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) {
                    Log.d(LogTag.TRANSACTION, "[HttpUtils] httpConn: xWapProfUrl=" + xWapProfileUrl);
                }
                req.addHeader(xWapProfileTagName, xWapProfileUrl);
            }
        }
        // Extra http parameters. Split by '|' to get a list of value pairs.
        // Separate each pair by the first occurrence of ':' to obtain a name and
        // value. Replace the occurrence of the string returned by
        // MmsConfig.getHttpParamsLine1Key() with the users telephone number inside
        // the value.
        String extraHttpParams = MmsConfig.getHttpParams();
        if (extraHttpParams != null) {
            String line1Number = ((TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE)).getLine1Number();
            String line1Key = MmsConfig.getHttpParamsLine1Key();
            String[] paramList = extraHttpParams.split("\\|");
            for (String paramPair : paramList) {
                String[] splitPair = paramPair.split(":", 2);
                if (splitPair.length == 2) {
                    String name = splitPair[0].trim();
                    String value = splitPair[1].trim();
                    if (line1Key != null) {
                        value = value.replace(line1Key, line1Number);
                    }
                    if (!TextUtils.isEmpty(name) && !TextUtils.isEmpty(value)) {
                        req.addHeader(name, value);
                    }
                }
            }
        }
        req.addHeader(HDR_KEY_ACCEPT_LANGUAGE, HDR_VALUE_ACCEPT_LANGUAGE);
        HttpResponse response = client.execute(target, req);
        StatusLine status = response.getStatusLine();
        if (status.getStatusCode() != 200) {
            // HTTP 200 is success.
            throw new IOException("HTTP error: " + status.getReasonPhrase());
        }
        HttpEntity entity = response.getEntity();
        byte[] body = null;
        if (entity != null) {
            try {
                if (entity.getContentLength() > 0) {
                    body = new byte[(int) entity.getContentLength()];
                    DataInputStream dis = new DataInputStream(entity.getContent());
                    try {
                        dis.readFully(body);
                    } finally {
                        try {
                            dis.close();
                        } catch (IOException e) {
                            Log.e(TAG, "Error closing input stream: " + e.getMessage());
                        }
                    }
                }
                if (entity.isChunked()) {
                    Log.v(TAG, "httpConnection: transfer encoding is chunked");
                    int bytesTobeRead = MmsConfig.getMaxMessageSize();
                    byte[] tempBody = new byte[bytesTobeRead];
                    DataInputStream dis = new DataInputStream(entity.getContent());
                    try {
                        int bytesRead = 0;
                        int offset = 0;
                        boolean readError = false;
                        do {
                            try {
                                bytesRead = dis.read(tempBody, offset, bytesTobeRead);
                            } catch (IOException e) {
                                readError = true;
                                Log.e(TAG, "httpConnection: error reading input stream" + e.getMessage());
                                break;
                            }
                            if (bytesRead > 0) {
                                bytesTobeRead -= bytesRead;
                                offset += bytesRead;
                            }
                        } while (bytesRead >= 0 && bytesTobeRead > 0);
                        if (bytesRead == -1 && offset > 0 && !readError) {
                            // offset is same as total number of bytes read
                            // bytesRead will be -1 if the data was read till the eof
                            body = new byte[offset];
                            System.arraycopy(tempBody, 0, body, 0, offset);
                            Log.v(TAG, "httpConnection: Chunked response length [" + Integer.toString(offset) + "]");
                        } else {
                            Log.e(TAG, "httpConnection: Response entity too large or empty");
                        }
                    } finally {
                        try {
                            dis.close();
                        } catch (IOException e) {
                            Log.e(TAG, "Error closing input stream: " + e.getMessage());
                        }
                    }
                }
            } finally {
                if (entity != null) {
                    entity.consumeContent();
                }
            }
        }
        return body;
    } catch (URISyntaxException e) {
        handleHttpConnectionException(e, url);
    } catch (IllegalStateException e) {
        handleHttpConnectionException(e, url);
    } catch (IllegalArgumentException e) {
        handleHttpConnectionException(e, url);
    } catch (SocketException e) {
        handleHttpConnectionException(e, url);
    } catch (Exception e) {
        handleHttpConnectionException(e, url);
    } finally {
        if (client != null) {
            client.close();
        }
    }
    return null;
}
Also used : HttpRequest(org.apache.http.HttpRequest) HttpPost(org.apache.http.client.methods.HttpPost) SocketException(java.net.SocketException) HttpEntity(org.apache.http.HttpEntity) HttpGet(org.apache.http.client.methods.HttpGet) HttpResponse(org.apache.http.HttpResponse) IOException(java.io.IOException) URISyntaxException(java.net.URISyntaxException) AndroidHttpClient(android.net.http.AndroidHttpClient) DataInputStream(java.io.DataInputStream) URI(java.net.URI) URISyntaxException(java.net.URISyntaxException) SocketException(java.net.SocketException) IOException(java.io.IOException) StatusLine(org.apache.http.StatusLine) HttpParams(org.apache.http.params.HttpParams) TelephonyManager(android.telephony.TelephonyManager) HttpHost(org.apache.http.HttpHost)

Aggregations

HttpRequest (org.apache.http.HttpRequest)155 HttpResponse (org.apache.http.HttpResponse)57 HttpContext (org.apache.http.protocol.HttpContext)56 HttpHost (org.apache.http.HttpHost)52 Test (org.junit.Test)40 IOException (java.io.IOException)36 Header (org.apache.http.Header)33 HttpException (org.apache.http.HttpException)33 HttpEntity (org.apache.http.HttpEntity)27 HttpEntityEnclosingRequest (org.apache.http.HttpEntityEnclosingRequest)25 BasicHttpRequest (org.apache.http.message.BasicHttpRequest)22 HttpGet (org.apache.http.client.methods.HttpGet)21 HttpPost (org.apache.http.client.methods.HttpPost)21 URI (java.net.URI)19 ProtocolException (org.apache.http.ProtocolException)18 AbortableHttpRequest (org.apache.http.client.methods.AbortableHttpRequest)16 StringEntity (org.apache.http.entity.StringEntity)16 ArrayList (java.util.ArrayList)14 NameValuePair (org.apache.http.NameValuePair)14 CredentialsProvider (org.apache.http.client.CredentialsProvider)14