Example usage for org.apache.http.client.methods HttpUriRequest getURI

List of usage examples for org.apache.http.client.methods HttpUriRequest getURI

Introduction

In this page you can find the example usage for org.apache.http.client.methods HttpUriRequest getURI.

Prototype

URI getURI();

Source Link

Document

Returns the URI this request uses, such as <code>http://example.org/path/to/file</code>.

Usage

From source file:com.joyent.manta.http.StandardHttpHelper.java

@Override
public MantaObjectInputStream httpRequestAsInputStream(final HttpUriRequest request,
        final MantaHttpHeaders requestHeaders) throws IOException {
    if (requestHeaders != null) {
        MantaHttpRequestFactory.addHeaders(request, requestHeaders.asApacheHttpHeaders());
    }//  w  ww  .ja v a2s . c o m

    final int expectedHttpStatus;

    if (requestHeaders != null && requestHeaders.containsKey(HttpHeaders.RANGE)) {
        expectedHttpStatus = HttpStatus.SC_PARTIAL_CONTENT;
    } else {
        expectedHttpStatus = HttpStatus.SC_OK;
    }

    final Function<CloseableHttpResponse, MantaObjectInputStream> responseAction = response -> {
        final MantaHttpHeaders responseHeaders = new MantaHttpHeaders(response.getAllHeaders());
        final String path = request.getURI().getPath();
        // MantaObjectResponse expects to be constructed with the
        // encoded path, which it then decodes when a caller does
        // getPath.  However, here the HttpUriRequest has already
        // decoded.
        final MantaObjectResponse metadata = new MantaObjectResponse(MantaUtils.formatPath(path),
                responseHeaders);

        if (metadata.isDirectory()) {
            final String msg = "Directories do not have data, so data streams "
                    + "from directories are not possible.";
            final MantaUnexpectedObjectTypeException exception = new MantaUnexpectedObjectTypeException(msg,
                    ObjectType.FILE, ObjectType.DIRECTORY);
            exception.setContextValue("path", path);

            if (metadata.getHttpHeaders() != null) {
                exception.setResponseHeaders(metadata.getHttpHeaders());
            }

            throw exception;
        }

        final HttpEntity entity = response.getEntity();
        if (entity == null) {
            final String msg = "Can't process null response entity.";
            final MantaClientException exception = new MantaClientException(msg);
            exception.setContextValue("uri", request.getRequestLine().getUri());
            exception.setContextValue("method", request.getRequestLine().getMethod());

            throw exception;
        }

        final InputStream httpEntityStream;
        try {
            httpEntityStream = entity.getContent();
        } catch (IOException ioe) {
            String msg = String.format("Error getting stream from entity content for path: %s", path);
            MantaObjectException e = new MantaObjectException(msg, ioe);
            e.setContextValue("path", path);
            HttpHelper.annotateContextedException(e, request, response);
            throw e;
        }

        final InputStream backingStream;
        final InputStreamContinuator continuator = constructContinuatorForCompatibleRequest(request, response);
        if (continuator != null) {
            backingStream = new AutoContinuingInputStream(httpEntityStream, continuator);
        } else {
            backingStream = httpEntityStream;
        }

        return new MantaObjectInputStream(metadata, response, backingStream);
    };

    return executeRequest(request, expectedHttpStatus, responseAction, false, "GET    {} response [{}] {} ");
}

From source file:com.hypers.frame.http.core.AsyncHttpClient.java

/**
 * Puts a new request in queue as a new thread in pool to be executed
 *
 * @param client          HttpClient to be used for request, can differ in single requests
 * @param contentType     MIME body type, for POST and PUT requests, may be null
 * @param context         Context of Android application, to hold the reference of request
 * @param httpContext     HttpContext in which the request will be executed
 * @param responseHandler ResponseHandler or its subclass to put the response into
 * @param uriRequest      instance of HttpUriRequest, which means it must be of HttpDelete,
 *                        HttpPost, HttpGet, HttpPut, etc.
 * @return RequestHandle of future request process
 *//*w  ww.  j a v a2 s .  c om*/
protected RequestHandle sendRequest(DefaultHttpClient client, HttpContext httpContext,
        HttpUriRequest uriRequest, String contentType, ResponseHandlerInterface responseHandler,
        Context context) {
    if (contentType != null) {
        uriRequest.setHeader("Content-Type", contentType);
    }
    //        //token
    //        uriRequest.addHeader("token", UserDataManger.getToken(context));

    responseHandler.setRequestHeaders(uriRequest.getAllHeaders());
    responseHandler.setRequestURI(uriRequest.getURI());

    Future<?> request = threadPool
            .submit(new AsyncHttpRequest(client, httpContext, uriRequest, responseHandler));

    if (context != null) {
        // Add request to request map
        List<WeakReference<Future<?>>> requestList = requestMap.get(context);
        if (requestList == null) {
            requestList = new LinkedList<WeakReference<Future<?>>>();
            requestMap.put(context, requestList);
        }

        requestList.add(new WeakReference<Future<?>>(request));

        // TODO: Remove dead weakrefs from requestLists?
    }

    return new RequestHandle(request);
}

From source file:org.vietspider.net.apache.DefaultRequestDirector.java

/**
 * Analyzes a response to check need for a followup.
 *
 * @param roureq    the request and route.
 * @param response  the response to analayze
 * @param context   the context used for the current request execution
 *
 * @return  the followup request and route if there is a followup, or
 *          <code>null</code> if the response should be returned as is
 *
 * @throws HttpException    in case of a problem
 * @throws IOException      in case of an IO problem
 */// ww  w. ja  v a2 s.  c om
protected RoutedRequest handleResponse(RoutedRequest roureq, HttpResponse response, HttpContext context)
        throws HttpException, IOException {

    HttpRoute route = roureq.getRoute();
    RequestWrapper request = roureq.getRequest();

    HttpParams params = request.getParams();
    if (HttpClientParams.isRedirecting(params)
            && this.redirectStrategy.isRedirected(request, response, context)) {

        if (redirectCount >= maxRedirects) {
            throw new RedirectException("Maximum redirects (" + maxRedirects + ") exceeded");
        }
        redirectCount++;

        // Virtual host cannot be used any longer
        virtualHost = null;

        HttpUriRequest redirect = redirectStrategy.getRedirect(request, response, context);
        HttpRequest orig = request.getOriginal();
        //            redirect.setHeaders(orig.getAllHeaders());
        //VietSpider fix bug
        URI uri = redirect.getURI();
        Header[] headers = orig.getAllHeaders();
        for (Header header : headers) {
            if ("host".equalsIgnoreCase(header.getName())) {
                redirect.addHeader(new BasicHeader("Host", uri.getHost()));
            } else {
                redirect.addHeader(header);
            }
        }

        if (uri.getHost() == null) {
            throw new ProtocolException("Redirect URI does not specify a valid host name: " + uri);
        }

        HttpHost newTarget = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());

        // Unset auth scope
        targetAuthState.setAuthScope(null);
        proxyAuthState.setAuthScope(null);

        // Invalidate auth states if redirecting to another host
        if (!route.getTargetHost().equals(newTarget)) {
            targetAuthState.invalidate();
            AuthScheme authScheme = proxyAuthState.getAuthScheme();
            if (authScheme != null && authScheme.isConnectionBased()) {
                proxyAuthState.invalidate();
            }
        }

        RequestWrapper wrapper = wrapRequest(redirect);
        wrapper.setParams(params);

        HttpRoute newRoute = determineRoute(newTarget, wrapper, context);
        RoutedRequest newRequest = new RoutedRequest(wrapper, newRoute);

        if (this.log.isDebugEnabled()) {
            this.log.debug("Redirecting to '" + uri + "' via " + newRoute);
        }

        return newRequest;
    }

    CredentialsProvider credsProvider = (CredentialsProvider) context
            .getAttribute(ClientContext.CREDS_PROVIDER);

    if (credsProvider != null && HttpClientParams.isAuthenticating(params)) {

        if (this.targetAuthHandler.isAuthenticationRequested(response, context)) {

            HttpHost target = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
            if (target == null) {
                target = route.getTargetHost();
            }

            this.log.debug("Target requested authentication");
            Map<String, Header> challenges = this.targetAuthHandler.getChallenges(response, context);
            try {
                processChallenges(challenges, this.targetAuthState, this.targetAuthHandler, response, context);
            } catch (AuthenticationException ex) {
                if (this.log.isWarnEnabled()) {
                    this.log.warn("Authentication error: " + ex.getMessage());
                    return null;
                }
            }
            updateAuthState(this.targetAuthState, target, credsProvider);

            if (this.targetAuthState.getCredentials() != null) {
                // Re-try the same request via the same route
                return roureq;
            } else {
                return null;
            }
        } else {
            // Reset target auth scope
            this.targetAuthState.setAuthScope(null);
        }

        if (this.proxyAuthHandler.isAuthenticationRequested(response, context)) {

            HttpHost proxy = route.getProxyHost();

            this.log.debug("Proxy requested authentication");
            Map<String, Header> challenges = this.proxyAuthHandler.getChallenges(response, context);
            try {
                processChallenges(challenges, this.proxyAuthState, this.proxyAuthHandler, response, context);
            } catch (AuthenticationException ex) {
                if (this.log.isWarnEnabled()) {
                    this.log.warn("Authentication error: " + ex.getMessage());
                    return null;
                }
            }
            updateAuthState(this.proxyAuthState, proxy, credsProvider);

            if (this.proxyAuthState.getCredentials() != null) {
                // Re-try the same request via the same route
                return roureq;
            } else {
                return null;
            }
        } else {
            // Reset proxy auth scope
            this.proxyAuthState.setAuthScope(null);
        }
    }
    return null;
}

From source file:nl.b3p.kaartenbalie.service.requesthandler.WFSRequestHandler.java

public void writeResponse(DataWrapper data, User user) throws Exception {
    OGCResponse ogcresponse = getNewOGCResponse();
    OGCRequest ogcrequest = data.getOgcrequest();

    String version = ogcrequest.getFinalVersion();
    String spInUrl = ogcrequest.getServiceProviderName();

    Integer[] orgIds = user.getOrganizationIds();
    OutputStream os = data.getOutputStream();

    Object identity = null;/*from w  ww  . j  ava  2 s .co m*/
    try {
        identity = MyEMFDatabase.createEntityManager(MyEMFDatabase.MAIN_EM);

        boolean forAdmin = isConfigInUrlAndAdmin(data, user);
        // zet layers uit request in een list
        List<LayerSummary> layerSummaryList = prepareRequestLayers(ogcrequest);
        if (layerSummaryList == null) {
            // als geen layers meegegeven, dan alle layers gebruiken
            // alleen bij getcapabilities
            EntityManager em = MyEMFDatabase.getEntityManager(MyEMFDatabase.MAIN_EM);
            String[] al = getOrganisationLayers(em, orgIds, version, forAdmin);
            layerSummaryList = LayerSummary.createLayerSummaryList(Arrays.asList(al), spInUrl, true);
        }

        // maak lijst waarin de layers per sp zijn verzameld
        // boolean om volgorde van de lagen te bewaren
        List<SpLayerSummary> spLayerSummaries = null;
        if (forAdmin) {
            spLayerSummaries = getLayerSummaries(layerSummaryList, spInUrl);
        } else {
            spLayerSummaries = getServiceProviderURLS(layerSummaryList, orgIds, false, data, false);
        }
        if (spLayerSummaries == null || spLayerSummaries.isEmpty()) {
            throw new UnsupportedOperationException(
                    "No Serviceprovider available! User might not have rights to any Serviceprovider!");
        }
        if (spLayerSummaries.size() > 1 && version.equals(OGCConstants.WFS_VERSION_UNSPECIFIED)) {
            // forceren dat alle sp dezelfde versie retourneren, indien meer dan 1
            ogcrequest.addOrReplaceParameter(OGCConstants.VERSION, OGCConstants.WFS_VERSION_110);
        }

        DataMonitoring rr = data.getRequestReporting();
        long startprocestime = System.currentTimeMillis();
        String xmlEncoding = "UTF-8";

        for (SpLayerSummary sp : spLayerSummaries) {
            if (spInUrl != null && !spInUrl.equals(sp.getSpAbbr())) {
                // sp in url en dit is een andere sp
                continue;
            }
            sp.setSpInUrl(spInUrl);

            // zet de juiste layers voor deze sp
            OGCRequest sprequest = (OGCRequest) ogcrequest.clone();
            prepareRequest4Sp(sprequest, sp);

            String lurl = sp.getSpUrl();
            if (lurl.length() == 0) {
                throw new UnsupportedOperationException("No Serviceprovider for this service available!");
            }
            ServiceProviderRequest wfsRequest = this.createServiceProviderRequest(data, lurl,
                    sp.getServiceproviderId(), 0l);

            B3PCredentials credentials = new B3PCredentials();
            credentials.setUserName(sp.getUsername());
            credentials.setPassword(sp.getPassword());
            credentials.setUrl(lurl);
            HttpClientConfigured hcc = new HttpClientConfigured(credentials);

            HttpUriRequest method = null;
            if (sprequest.getHttpMethod().equalsIgnoreCase("POST")) {
                method = createPostMethod(sprequest, sp, wfsRequest);
            } else { // get
                method = createGetMethod(sprequest, sp, wfsRequest);
            }

            try {
                HttpResponse response = hcc.execute(method);

                try {

                    int statusCode = response.getStatusLine().getStatusCode();
                    wfsRequest.setResponseStatus(statusCode);
                    HttpEntity entity = response.getEntity();

                    if (statusCode != 200) {
                        log.error("Failed to connect with " + method.getURI() + " Using body: "
                                + sprequest.getXMLBody());
                        throw new UnsupportedOperationException("Failed to connect with " + method.getURI()
                                + " Using body: " + sprequest.getXMLBody());
                    }

                    wfsRequest.setRequestResponseTime(System.currentTimeMillis() - startprocestime);

                    data.setContentType("text/xml");
                    InputStream is = entity.getContent();

                    InputStream isx = null;
                    byte[] bytes = null;
                    int rsl = 0;
                    try {
                        rsl = new Integer(KBConfiguration.RESPONSE_SIZE_LIMIT);
                    } catch (NumberFormatException nfe) {
                        log.debug("KBConfiguration.RESPONSE_SIZE_LIMIT not properly configured: "
                                + nfe.getLocalizedMessage());
                    }
                    if (KBConfiguration.SAVE_MESSAGES) {
                        int len = 1;
                        byte[] buffer = new byte[2024];
                        ByteArrayOutputStream bos = new ByteArrayOutputStream();
                        while ((len = is.read(buffer, 0, buffer.length)) > 0) {
                            bos.write(buffer, 0, len);
                            if (buffer.length > rsl && rsl > 0) {
                                throw new ProviderException(
                                        "Response size exceeds maximum set in configuration:" + buffer.length
                                                + ", max is: " + rsl);
                            }
                        }
                        bytes = bos.toByteArray();
                        isx = new ByteArrayInputStream(bytes);
                    } else {
                        isx = new CountingInputStream(is);
                    }

                    if (KBConfiguration.SAVE_MESSAGES || spInUrl == null || !mayDirectWrite()) {
                        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                        dbf.setNamespaceAware(true);
                        DocumentBuilder builder = dbf.newDocumentBuilder();
                        Document doc = builder.parse(isx);
                        // indien meerdere sp met verschillende encodings
                        // dan wint de laatste!
                        String docEncoding = doc.getXmlEncoding();
                        if (docEncoding != null) {
                            xmlEncoding = docEncoding;
                        }

                        int len = 0;
                        if (KBConfiguration.SAVE_MESSAGES) {
                            wfsRequest.setMessageReceived(new String(bytes));
                        } else {
                            len = new Integer(((CountingInputStream) isx).getCount());
                            wfsRequest.setBytesReceived(new Long(len));
                        }
                        if (len > rsl && rsl > 0) {
                            throw new ProviderException("Response size exceeds maximum set in configuration:"
                                    + len + ", max is: " + rsl);
                        }

                        String prefix = sp.getSpAbbr();
                        if (spInUrl != null && !spInUrl.isEmpty()) {
                            // sp in url dus geen prefix toevoegen
                            prefix = null;
                        }

                        if (OGCResponse.isWfsV100ErrorResponse(doc.getDocumentElement())) {
                            // wfs 1.0.0 error
                            ogcresponse.rebuildWfsV100ErrorResponse(doc, sprequest, prefix);
                        } else if (OGCResponse.isOwsV100ErrorResponse(doc.getDocumentElement())) {
                            // wfs 1.1.0 error
                            ogcresponse.rebuildOwsV100ErrorResponse(doc, sprequest, prefix);
                        } else {
                            // normale response
                            ogcresponse.rebuildResponse(doc, sprequest, prefix);
                        }
                    } else {
                        /**
                         * Deze methode kan alleen aangeroepen worden als
                         * aan de volgende voorwaarden is voldaan:
                         * <li> slechts n sp nodig voor aanroep
                         * <li> spabbr zit in de url en niet als prefix in
                         * de layer name
                         * <li> KBConfiguration.SAVE_MESSAGES is false Als
                         * aan voorwaarden is voldaan dat wordt direct
                         * doorgestreamd indien er geen fout is opgetreden.
                         * <li> de aanroep methode mayDirectWrite is true.
                         */
                        // direct write possible
                        byte[] h = prepareDirectWrite(isx);
                        if (h != null) {
                            os.write(h);
                        }
                        // write rest
                        IOUtils.copy(isx, os);
                        wfsRequest.setBytesReceived(new Long(((CountingInputStream) isx).getCount()));
                        ogcresponse.setAlreadyDirectWritten(true);
                        break;
                    }
                } finally {
                    hcc.close(response);
                    hcc.close();
                }

            } catch (Exception e) {
                wfsRequest.setExceptionMessage("Failed to send bytes to client: " + e.getMessage());
                wfsRequest.setExceptionClass(e.getClass());

                throw e;
            } finally {
                rr.addServiceProviderRequest(wfsRequest);
            }
        }

        // only write when not already direct written
        if (!ogcresponse.isAlreadyDirectWritten()) {
            String responseBody = ogcresponse.getResponseBody(spLayerSummaries, ogcrequest, xmlEncoding);
            if (responseBody != null && !responseBody.equals("")) {
                byte[] buffer = responseBody.getBytes(xmlEncoding);
                os.write(buffer);
            } else {
                throw new UnsupportedOperationException("XMLbody empty!");
            }
        }
        doAccounting(user.getMainOrganizationId(), data, user);

    } finally {
        log.debug("Closing entity manager .....");
        MyEMFDatabase.closeEntityManager(identity, MyEMFDatabase.MAIN_EM);
    }
}

From source file:cn.kuwo.sing.phone4tv.commons.http.AsyncHttpClient.java

protected void sendRequest(DefaultHttpClient client, HttpContext httpContext, HttpUriRequest uriRequest,
        String contentType, AsyncHttpResponseHandler responseHandler, Context context) {
    if (contentType != null) {
        uriRequest.addHeader("Content-Type", contentType);
    }/*from ww  w.j  av  a2  s .co  m*/

    Future<?> request = threadPool
            .submit(new AsyncHttpRequest(client, httpContext, uriRequest, responseHandler));

    if (context != null) {
        // Add request to request map
        List<WeakReference<Future<?>>> requestList = requestMap.get(context);
        if (requestList == null) {
            requestList = new LinkedList<WeakReference<Future<?>>>();
            requestMap.put(context, requestList);
        }

        requestList.add(new WeakReference<Future<?>>(request));

        // TODO: Remove dead weakrefs from requestLists?
    }

    Log.d("AsyncHttpClient", "sendRequest: " + uriRequest.getURI().toString());
}

From source file:org.opencastproject.loadtest.engage.util.TrustedHttpClient.java

/**
 * {@inheritDoc}/*from  ww w  .jav a2s  . co m*/
 * @see org.opencastproject.loadtest.engage.util.remotetest.util.security.api.TrustedHttpClient#execute(org.apache.http.client.methods.HttpUriRequest)
 */
public HttpResponse execute(HttpUriRequest httpUriRequest) {
    // Add the request header to elicit a digest auth response
    httpUriRequest.addHeader(REQUESTED_AUTH_HEADER, DIGEST_AUTH);

    if ("GET".equalsIgnoreCase(httpUriRequest.getMethod())
            || "HEAD".equalsIgnoreCase(httpUriRequest.getMethod())) {
        // Set the user/pass
        UsernamePasswordCredentials creds = new UsernamePasswordCredentials(user, pass);
        httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY, creds);

        // Run the request (the http client handles the multiple back-and-forth requests)
        try {
            return httpClient.execute(httpUriRequest);
        } catch (IOException e) {
            throw new TrustedHttpClientException(e);
        }
    }

    // HttpClient doesn't handle the request dynamics for other verbs (especially when sending a streamed multipart
    // request), so we need to handle the details of the digest auth back-and-forth manually
    HttpRequestBase digestRequest;
    try {
        digestRequest = (HttpRequestBase) httpUriRequest.getClass().newInstance();
    } catch (Exception e) {
        throw new IllegalStateException("Can not create a new " + httpUriRequest.getClass().getName());
    }
    digestRequest.setURI(httpUriRequest.getURI());
    digestRequest.addHeader(REQUESTED_AUTH_HEADER, DIGEST_AUTH);
    String[] realmAndNonce = getRealmAndNonce(digestRequest);

    if (realmAndNonce != null) {
        // Set the user/pass
        UsernamePasswordCredentials creds = new UsernamePasswordCredentials(user, pass);

        // Set up the digest authentication with the required values
        DigestScheme digestAuth = new DigestScheme();
        digestAuth.overrideParamter("realm", realmAndNonce[0]);
        digestAuth.overrideParamter("nonce", realmAndNonce[1]);

        // Add the authentication header
        try {
            httpUriRequest.addHeader(digestAuth.authenticate(creds, httpUriRequest));
        } catch (Exception e) {
            // close the http connection(s)
            httpClient.getConnectionManager().shutdown();
            throw new TrustedHttpClientException(e);
        }
    }
    try {
        return httpClient.execute(httpUriRequest);
    } catch (Exception e) {
        // close the http connection(s)
        httpClient.getConnectionManager().shutdown();
        throw new TrustedHttpClientException(e);
    }
}

From source file:com.joyent.manta.http.StandardHttpHelper.java

@Override
public <R> R executeRequest(final HttpUriRequest request, final Integer expectedStatusCode,
        final Function<CloseableHttpResponse, R> responseAction, final boolean closeResponse,
        final String logMessage, final Object... logParameters) throws IOException {
    Validate.notNull(request, "Request object must not be null");

    CloseableHttpClient client = connectionContext.getHttpClient();

    CloseableHttpResponse response = client.execute(request);
    try {/*from  w w w. ja va 2  s  .c  om*/
        StatusLine statusLine = response.getStatusLine();

        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug(logMessage, logParameters, statusLine.getStatusCode(), statusLine.getReasonPhrase());
        }

        if (isFailedStatusCode(expectedStatusCode, statusLine)) {
            throw new MantaClientHttpResponseException(request, response, request.getURI().getPath());
        }

        if (responseAction != null) {
            return responseAction.apply(response);
        } else {
            return null;
        }
    } finally {
        if (closeResponse) {
            IOUtils.closeQuietly(response);
        }
    }
}

From source file:github.daneren2005.dsub.service.RESTMusicService.java

private void detectRedirect(String originalUrl, Context context, HttpContext httpContext) {
    HttpUriRequest request = (HttpUriRequest) httpContext.getAttribute(ExecutionContext.HTTP_REQUEST);
    HttpHost host = (HttpHost) httpContext.getAttribute(ExecutionContext.HTTP_TARGET_HOST);

    // Sometimes the request doesn't contain the "http://host" part
    String redirectedUrl;//from w ww.  jav  a  2s . com
    if (request.getURI().getScheme() == null) {
        redirectedUrl = host.toURI() + request.getURI();
    } else {
        redirectedUrl = request.getURI().toString();
    }

    redirectFrom = originalUrl.substring(0, originalUrl.indexOf("/rest/"));
    redirectTo = redirectedUrl.substring(0, redirectedUrl.indexOf("/rest/"));

    if (redirectFrom.compareTo(redirectTo) != 0) {
        Log.i(TAG, redirectFrom + " redirects to " + redirectTo);
    }
    redirectionLastChecked = System.currentTimeMillis();
    redirectionNetworkType = getCurrentNetworkType(context);
}

From source file:czd.lib.network.AsyncHttpClient.java

/**
 * Puts a new request in queue as a new thread in pool to be executed
 *
 * @param client          HttpClient to be used for request, can differ in single requests
 * @param contentType     MIME body type, for POST and PUT requests, may be null
 * @param context         Context of Android application, to hold the reference of request
 * @param httpContext     HttpContext in which the request will be executed
 * @param responseHandler ResponseHandler or its subclass to put the response into
 * @param uriRequest      instance of HttpUriRequest, which means it must be of HttpDelete,
 *                        HttpPost, HttpGet, HttpPut, etc.
 *
 * @return RequestHandle of future request process
 *///from w ww .  ja va  2 s. c o  m
protected RequestHandle sendRequest(DefaultHttpClient client, HttpContext httpContext,
        HttpUriRequest uriRequest, String contentType, ResponseHandlerInterface responseHandler,
        Context context) {
    if (contentType != null) {
        uriRequest.setHeader("Content-Type", contentType);
    }

    if (responseHandler instanceof RangeFileAsyncHttpResponseHandler)
        ((RangeFileAsyncHttpResponseHandler) responseHandler).updateRequestHeaders(uriRequest);
    responseHandler.setRequestHeaders(uriRequest.getAllHeaders());
    responseHandler.setRequestURI(uriRequest.getURI());

    Future<?> request = threadPool
            .submit(new AsyncHttpRequest(client, httpContext, uriRequest, responseHandler));

    if (context != null) {
        // Add request to request map
        List<WeakReference<Future<?>>> requestList = requestMap.get(context);
        if (requestList == null) {
            requestList = new LinkedList<WeakReference<Future<?>>>();
            requestMap.put(context, requestList);
        }

        requestList.add(new WeakReference<Future<?>>(request));

        // TODO: Remove dead weakrefs from requestLists?
    }

    return new RequestHandle(request);
}

From source file:com.googlecode.jdeltasync.DeltaSyncClient.java

/**
 * Slightly modified version of {@link DefaultRedirectStrategy#getLocationURI(HttpRequest, HttpResponse, HttpContext)}
 * which also adds the query string from the original request URI to the new URI.
 *//*  ww  w.  ja va 2  s.c om*/
private URI getRedirectLocationURI(IDeltaSyncSession session, HttpUriRequest request, HttpResponse response,
        HttpContext context) throws DeltaSyncException {

    //get the location header to find out where to redirect to
    Header locationHeader = response.getFirstHeader("location");
    if (locationHeader == null) {
        // got a redirect response, but no location header
        throw new DeltaSyncException(
                "Received redirect response " + response.getStatusLine() + " but no location header");
    }
    String location = locationHeader.getValue();
    if (session.getLogger().isDebugEnabled()) {
        session.getLogger().debug("Redirect requested to location '" + location + "'");
    }

    URI uri = null;
    try {
        uri = new URI(location);
        if (request.getURI().getRawQuery() != null) {
            String query = request.getURI().getRawQuery();
            uri = new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(), uri.getPath(),
                    query, uri.getFragment());
        }
    } catch (URISyntaxException ex) {
        throw new DeltaSyncException("Invalid redirect URI: " + location, ex);
    }

    final HttpClientContext clientContext = HttpClientContext.adapt(context);
    final RequestConfig config = clientContext.getRequestConfig();

    // rfc2616 demands the location value be a complete URI
    // Location       = "Location" ":" absoluteURI
    try {
        if (!uri.isAbsolute()) {
            if (config.isRelativeRedirectsAllowed()) {
                throw new DeltaSyncException("Relative redirect location '" + uri + "' not allowed");
            }
            // Adjust location URI
            HttpHost target = clientContext.getTargetHost();
            if (target == null) {
                throw new IllegalStateException("Target host not available " + "in the HTTP context");
            }

            URI requestURI = new URI(request.getRequestLine().getUri());
            URI absoluteRequestURI = URIUtils.rewriteURI(requestURI, target, false);
            uri = URIUtils.resolve(absoluteRequestURI, uri);
        }
    } catch (URISyntaxException ex) {
        throw new DeltaSyncException(ex.getMessage(), ex);
    }

    RedirectLocations redirectLocations = (RedirectLocations) clientContext
            .getAttribute("http.protocol.redirect-locations");
    if (redirectLocations == null) {
        redirectLocations = new RedirectLocations();
        context.setAttribute("http.protocol.redirect-locations", redirectLocations);
    }

    if (config.isCircularRedirectsAllowed()) {
        URI redirectURI;
        if (uri.getFragment() != null) {
            try {
                HttpHost target = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());
                redirectURI = URIUtils.rewriteURI(uri, target, true);
            } catch (URISyntaxException ex) {
                throw new DeltaSyncException(ex.getMessage(), ex);
            }
        } else {
            redirectURI = uri;
        }

        if (redirectLocations.contains(redirectURI)) {
            throw new DeltaSyncException("Circular redirect to '" + redirectURI + "'");
        } else {
            redirectLocations.add(redirectURI);
        }
    }

    return uri;
}