Example usage for org.apache.http.impl.client EntityEnclosingRequestWrapper EntityEnclosingRequestWrapper

List of usage examples for org.apache.http.impl.client EntityEnclosingRequestWrapper EntityEnclosingRequestWrapper

Introduction

In this page you can find the example usage for org.apache.http.impl.client EntityEnclosingRequestWrapper EntityEnclosingRequestWrapper.

Prototype

public EntityEnclosingRequestWrapper(final HttpEntityEnclosingRequest request) throws ProtocolException 

Source Link

Usage

From source file:com.microsoft.services.orc.http.impl.AndroidNetworkRunnable.java

@Override
public void run() {
    AndroidHttpClient client = null;/*from w  w w  .j a  va2  s  .  com*/
    try {

        String userAgent = mRequest.getHeaders().get(Constants.USER_AGENT_HEADER);

        if (userAgent == null) {
            userAgent = "";
        }

        client = AndroidHttpClient.newInstance(userAgent);

        BasicHttpEntityEnclosingRequest realRequest = new BasicHttpEntityEnclosingRequest(
                mRequest.getVerb().toString(), mRequest.getUrl().toString());
        EntityEnclosingRequestWrapper wrapper = new EntityEnclosingRequestWrapper(realRequest);

        Map<String, String> headers = mRequest.getHeaders();
        for (String key : headers.keySet()) {
            wrapper.addHeader(key, headers.get(key));
        }

        if (mRequest.getContent() != null) {
            ByteArrayEntity entity = new ByteArrayEntity(mRequest.getContent());
            wrapper.setEntity(entity);
        } else if (mRequest.getStreamedContent() != null) {
            InputStream stream = mRequest.getStreamedContent();
            InputStreamEntity entity = new InputStreamEntity(stream, mRequest.getStreamedContentSize());
            wrapper.setEntity(entity);
        }

        HttpResponse realResponse = client.execute(wrapper);
        int status = realResponse.getStatusLine().getStatusCode();

        Map<String, List<String>> responseHeaders = new HashMap<String, List<String>>();
        for (Header header : realResponse.getAllHeaders()) {
            List<String> headerValues = new ArrayList<String>();
            for (HeaderElement element : header.getElements()) {
                headerValues.add(element.getValue());
            }
            responseHeaders.put(header.getName(), headerValues);
        }

        HttpEntity entity = realResponse.getEntity();
        InputStream stream = null;

        if (entity != null) {
            stream = entity.getContent();
        }

        if (stream != null) {
            final AndroidHttpClient finalClient = client;
            Closeable closeable = new Closeable() {
                @Override
                public void close() throws IOException {
                    finalClient.close();
                }
            };

            Response response = new ResponseImpl(stream, status, responseHeaders, closeable);

            mFuture.set(response);
        } else {
            client.close();
            mFuture.set(new EmptyResponse(status, responseHeaders));
        }

    } catch (Throwable t) {
        if (client != null) {
            client.close();
        }

        mFuture.setException(t);
    }
}

From source file:com.google.android.net.GoogleHttpClient.java

/**
 * Wraps the request making it mutable./*  w w  w .  j ava2s.  c o m*/
 */
private static RequestWrapper wrapRequest(HttpUriRequest request) throws IOException {
    try {
        // We have to wrap it with the right type. Some code performs
        // instanceof checks.
        RequestWrapper wrapped;
        if (request instanceof HttpEntityEnclosingRequest) {
            wrapped = new EntityEnclosingRequestWrapper((HttpEntityEnclosingRequest) request);
        } else {
            wrapped = new RequestWrapper(request);
        }

        // Copy the headers from the original request into the wrapper.
        wrapped.resetHeaders();

        return wrapped;
    } catch (ProtocolException e) {
        throw new ClientProtocolException(e);
    }
}

From source file:com.microsoft.windowsazure.messaging.Connection.java

/**
 * Executes a request to the Notification Hub server
 * @param resource   The resource to access
 * @param content   The request content body
 * @param contentType   The request content type
 * @param method   The request method// w  w w  .  j  a  v a  2  s  . co  m
 * @param targetHeaderName The header name when we need to get value from it in instead of content
 * @param extraHeaders   Extra headers to include in the request
 * @return   The response content body
 * @throws Exception
 */
public String executeRequest(String resource, String content, String contentType, String method,
        String targetHeaderName, Header... extraHeaders) throws Exception {
    URI endpointURI = URI.create(mConnectionData.get(ENDPOINT_KEY));
    String scheme = endpointURI.getScheme();

    // Replace the scheme with "https"
    String url = "https" + endpointURI.toString().substring(scheme.length());
    if (!url.endsWith("/")) {
        url += "/";
    }

    url += resource;

    url = AddApiVersionToUrl(url);

    BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest(method, url);

    if (!Utils.isNullOrWhiteSpace(content)) {
        request.setEntity(new StringEntity(content, UTF8_ENCODING));
    }

    request.addHeader(HTTP.CONTENT_TYPE, contentType);
    EntityEnclosingRequestWrapper wrapper = new EntityEnclosingRequestWrapper(request);

    if (extraHeaders != null) {
        for (Header header : extraHeaders) {
            wrapper.addHeader(header);
        }
    }

    return executeRequest(wrapper, targetHeaderName);
}

From source file:com.netscape.certsrv.client.PKIConnection.java

public PKIConnection(ClientConfig config) {

    this.config = config;

    // Register https scheme.
    Scheme scheme = new Scheme("https", 443, new JSSProtocolSocketFactory());
    httpClient.getConnectionManager().getSchemeRegistry().register(scheme);

    // Don't retry operations.
    httpClient.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(0, false));

    if (config.getUsername() != null && config.getPassword() != null) {
        List<String> authPref = new ArrayList<String>();
        authPref.add(AuthPolicy.BASIC);/*w ww.  j a  v a 2s. c om*/
        httpClient.getParams().setParameter(AuthPNames.PROXY_AUTH_PREF, authPref);

        httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials(config.getUsername(), config.getPassword()));
    }

    httpClient.addRequestInterceptor(new HttpRequestInterceptor() {
        @Override
        public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {

            requestCounter++;

            if (verbose) {
                System.out.println("HTTP request: " + request.getRequestLine());
                for (Header header : request.getAllHeaders()) {
                    System.out.println("  " + header.getName() + ": " + header.getValue());
                }
            }

            if (output != null) {
                File file = new File(output, "http-request-" + requestCounter);
                storeRequest(file, request);
            }

            // Set the request parameter to follow redirections.
            HttpParams params = request.getParams();
            if (params instanceof ClientParamsStack) {
                ClientParamsStack paramsStack = (ClientParamsStack) request.getParams();
                params = paramsStack.getRequestParams();
            }
            HttpClientParams.setRedirecting(params, true);
        }
    });

    httpClient.addResponseInterceptor(new HttpResponseInterceptor() {
        @Override
        public void process(HttpResponse response, HttpContext context) throws HttpException, IOException {

            responseCounter++;

            if (verbose) {
                System.out.println("HTTP response: " + response.getStatusLine());
                for (Header header : response.getAllHeaders()) {
                    System.out.println("  " + header.getName() + ": " + header.getValue());
                }
            }

            if (output != null) {
                File file = new File(output, "http-response-" + responseCounter);
                storeResponse(file, response);
            }
        }
    });

    httpClient.setRedirectStrategy(new DefaultRedirectStrategy() {
        @Override
        public HttpUriRequest getRedirect(HttpRequest request, HttpResponse response, HttpContext context)
                throws ProtocolException {

            HttpUriRequest uriRequest = super.getRedirect(request, response, context);

            URI uri = uriRequest.getURI();
            if (verbose)
                System.out.println("HTTP redirect: " + uri);

            // Redirect the original request to the new URI.
            RequestWrapper wrapper;
            if (request instanceof HttpEntityEnclosingRequest) {
                wrapper = new EntityEnclosingRequestWrapper((HttpEntityEnclosingRequest) request);
            } else {
                wrapper = new RequestWrapper(request);
            }
            wrapper.setURI(uri);

            return wrapper;
        }

        @Override
        public boolean isRedirected(HttpRequest request, HttpResponse response, HttpContext context)
                throws ProtocolException {

            // The default redirection policy does not redirect POST or PUT.
            // This overrides the policy to follow redirections for all HTTP methods.
            return response.getStatusLine().getStatusCode() == 302;
        }
    });

    engine = new ApacheHttpClient4Engine(httpClient);

    resteasyClient = new ResteasyClientBuilder().httpEngine(engine).build();
    resteasyClient.register(PKIRESTProvider.class);
}

From source file:com.klarna.checkout.stubs.HttpClientStub.java

/**
 * Stubbed Execute implementation./*from  w  w  w  .j  a  v a 2s.  c om*/
 *
 * @param <T> The class ResponseHandler operates on
 * @param hur HttpUriRequest object
 * @param rh ResponseHandler object
 * @param hc HttpContext holder
 *
 * @return ResponseHandler result
 *
 * @throws IOException never
 */
@Override
public <T> T execute(final HttpUriRequest hur, final ResponseHandler<? extends T> rh, final HttpContext hc)
        throws IOException {
    this.httpUriReq = hur;

    List<Integer> redirects = new ArrayList();
    redirects.add(301);
    redirects.add(302);
    redirects.add(303);
    this.visited.clear();
    if (this.httpUriReq instanceof HttpEntityEnclosingRequest) {
        try {
            this.httpUriReq = new EntityEnclosingRequestWrapper((HttpEntityEnclosingRequest) hur);
        } catch (ProtocolException ex) {
            throw new IOException(ex);
        }
    }
    int status;
    do {
        try {
            for (HttpRequestInterceptor hri : requestInterceptors) {
                hri.process(this.httpUriReq, hc);
            }
        } catch (HttpException ex) {
            throw new ClientProtocolException(ex);
        }

        if (!this.visited.add(this.httpUriReq.getURI())) {
            throw new ClientProtocolException(new CircularRedirectException());
        }

        this.lastResponse = this.getResponse();

        if (this.lastResponse.getStatusLine().getStatusCode() < 400) {
            fixData();
        }

        try {
            for (HttpResponseInterceptor hri : responseInterceptors) {
                hri.process(this.lastResponse, hc);
            }
        } catch (HttpException ex) {
            throw new ClientProtocolException(ex);
        }
        status = this.lastResponse.getStatusLine().getStatusCode();
        Header location = this.lastResponse.getLastHeader("Location");
        if (location != null) {
            this.httpUriReq = new HttpGet(location.getValue());
        }
    } while (redirects.contains(status));

    if (this.data.containsKey("test")) {
        ByteArrayInputStream bis = new ByteArrayInputStream(JSONObject.toJSONString(data).getBytes());
        this.lastResponse.setEntity(new InputStreamEntity(bis, bis.available()));
    }

    return rh.handleResponse(this.lastResponse);
}

From source file:org.robolectric.shadows.httpclient.DefaultRequestDirector.java

private RequestWrapper wrapRequest(final HttpRequest request) throws ProtocolException {
    if (request instanceof HttpEntityEnclosingRequest) {
        return new EntityEnclosingRequestWrapper((HttpEntityEnclosingRequest) request);
    } else {//  w w  w  . j a  v  a  2 s .  c  o m
        return new RequestWrapper(request);
    }
}

From source file:org.apache.http.impl.nio.client.DefaultAsyncRequestDirector.java

private RequestWrapper wrapRequest(final HttpRequest request) throws ProtocolException {
    if (request instanceof HttpEntityEnclosingRequest) {
        return new EntityEnclosingRequestWrapper((HttpEntityEnclosingRequest) request);
    }//w  ww  . j  a  v  a 2s . c  o  m
    return new RequestWrapper(request);
}