Example usage for org.apache.http.client.methods HttpRequestBase setURI

List of usage examples for org.apache.http.client.methods HttpRequestBase setURI

Introduction

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

Prototype

public void setURI(final URI uri) 

Source Link

Usage

From source file:com.dongfang.net.http.HttpHandler.java

@SuppressWarnings("unchecked")
private ResponseInfo<T> handleResponse(HttpResponse response) throws HttpException, IOException {
    if (response == null) {
        throw new HttpException("response is null");
    }/*from   w w w.  j a  va 2  s.c o m*/
    if (isCancelled())
        return null;

    StatusLine status = response.getStatusLine();
    int statusCode = status.getStatusCode();
    if (statusCode < 300) {
        Object result = null;
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            isUploading = false;
            if (isDownloadingFile) {
                autoResume = autoResume && OtherUtils.isSupportRange(response);
                String responseFileName = autoRename ? OtherUtils.getFileNameFromHttpResponse(response) : null;
                result = mFileDownloadHandler.handleEntity(entity, this, fileSavePath, autoResume,
                        responseFileName);
            } else {

                // Set charset from response header info if it's exist.
                String responseCharset = OtherUtils.getCharsetFromHttpResponse(response);
                charset = TextUtils.isEmpty(responseCharset) ? charset : responseCharset;

                result = mStringDownloadHandler.handleEntity(entity, this, charset);
                ULog.d(result.toString());
                // -------- token ?ip??token ,by dongfang, 2013-10-16 17:38:40----------------------
                if (isNewToken(result.toString())) {
                    String newUrl = requestUrl.replace(User.SHAREDPREFERENCES_ACCESS_TOKEN_OLD,
                            User.SHAREDPREFERENCES_ACCESS_TOKEN_NEW);
                    request.setURI(URI.create(newUrl));
                    return handleResponse(client.execute(request, context));
                }
                // ---------------------------------------------------------------------------------------------------
                // ?? by dongfang, 2013-10-16 17:38:40
                // HttpUtils.sHttpGetCache.put(_getRequestUrl, (String) responseBody, expiry);
                // ---------------------------------------------------------------------------------------------------
            }
        }
        return new ResponseInfo<T>(response, (T) result, false);
    } else if (statusCode == 301 || statusCode == 302) {
        if (httpRedirectHandler == null) {
            httpRedirectHandler = new DefaultHttpRedirectHandler();
        }
        HttpRequestBase request = httpRedirectHandler.getDirectRequest(response);
        if (request != null) {
            return this.sendRequest(request);
        }
    } else if (statusCode == 416) {
        throw new HttpException(statusCode, "maybe the file has downloaded completely");
    } else {
        throw new HttpException(statusCode, status.getReasonPhrase());
    }
    return null;
}

From source file:com.tealeaf.util.HTTP.java

public Response makeRequest(Methods method, URI uri, HashMap<String, String> requestHeaders, String data) {

    HttpRequestBase request = null;

    try {/*  w w  w  . ja va 2  s  . com*/
        if (method == Methods.GET) {
            request = new HttpGet();
        } else if (method == Methods.POST) {
            request = new HttpPost();
            if (data != null) {
                ((HttpPost) request).setEntity(new StringEntity(data, "UTF-8"));
            }
        } else if (method == Methods.PUT) {
            request = new HttpPut();
            if (data != null) {
                ((HttpPut) request).setEntity(new StringEntity(data, "UTF-8"));
            }
        } else if (method == Methods.DELETE) {
            request = new HttpDelete();
        } else if (method == Methods.HEAD) {
            request = new HttpHead();
        }
    } catch (UnsupportedEncodingException e) {
        logger.log(e);
    }
    request.setURI(uri);
    AndroidHttpClient client = AndroidHttpClient.newInstance(userAgent);
    if (requestHeaders != null) {
        for (Map.Entry<String, String> entry : requestHeaders.entrySet()) {
            request.addHeader(new BasicHeader(entry.getKey(), entry.getValue()));
        }
    }

    HttpResponse response = null;
    Response retVal = new Response();
    retVal.headers = new HashMap<String, String>();
    try {
        response = client.execute(request, localContext);
    } catch (SocketTimeoutException e) {
        // forget it--we don't care that the user couldn't connect
        // TODO hand this back as an error to JS
    } catch (IOException e) {
        if (!caughtIOException) {
            caughtIOException = true;
            logger.log(e);
        }
    } catch (Exception e) {
        logger.log(e);
    }
    if (response != null) {
        retVal.status = response.getStatusLine().getStatusCode();
        retVal.body = readContent(response);
        for (Header header : response.getAllHeaders()) {
            retVal.headers.put(header.getName(), header.getValue());
        }
    }
    client.close();
    return retVal;
}

From source file:com.web.server.ProxyServlet.java

@Override
@SuppressWarnings("unchecked")
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    // Create new client to perform the proxied request
    HttpClient httpclient = new DefaultHttpClient();

    // Determine final URL
    StringBuffer uri = new StringBuffer();
    uri.append(targetServer);//from w  w  w  .jav a2s . c  om
    uri.append(req.getRequestURI());

    // Add any supplied query strings
    String queryString = req.getQueryString();
    if (queryString != null) {
        uri.append("?" + queryString);
    }

    // Get HTTP method
    final String method = req.getMethod();
    // Create new HTTP request container
    HttpRequestBase request = null;

    // Get content length
    int contentLength = req.getContentLength();
    // Unknown content length ...
    //       if (contentLength == -1)
    //          throw new ServletException("Cannot handle unknown content length");
    // If we don't have an entity body, things are quite simple
    if (contentLength < 1) {
        request = new HttpRequestBase() {
            public String getMethod() {
                return method;
            }
        };
    } else {
        // Prepare request
        HttpEntityEnclosingRequestBase tmpRequest = new HttpEntityEnclosingRequestBase() {
            public String getMethod() {
                return method;
            }
        };

        // Transfer entity body from the received request to the new request
        InputStreamEntity entity = new InputStreamEntity(req.getInputStream(), contentLength);
        tmpRequest.setEntity(entity);

        request = tmpRequest;
    }

    // Set URI
    try {
        request.setURI(new URI(uri.toString()));
    } catch (URISyntaxException e) {
        throw new ServletException("URISyntaxException: " + e.getMessage());
    }

    // Copy headers from old request to new request
    // @todo not sure how this handles multiple headers with the same name
    Enumeration<String> headers = req.getHeaderNames();
    while (headers.hasMoreElements()) {
        String headerName = headers.nextElement();
        String headerValue = req.getHeader(headerName);
        // Skip Content-Length and Host
        String lowerHeader = headerName.toLowerCase();
        if (lowerHeader.equals("content-length") == false && lowerHeader.equals("host") == false) {
            //             System.out.println(headerName.toLowerCase() + ": " + headerValue);
            request.addHeader(headerName, headerValue);
        }
    }

    // Execute the request
    HttpResponse response = httpclient.execute(request);

    // Transfer status code to the response
    StatusLine status = response.getStatusLine();
    resp.setStatus(status.getStatusCode());
    // resp.setStatus(status.getStatusCode(), status.getReasonPhrase()); // This seems to be deprecated. Yes status message is "ambigous", but I don't approve

    // Transfer headers to the response
    Header[] responseHeaders = response.getAllHeaders();
    for (int i = 0; i < responseHeaders.length; i++) {
        Header header = responseHeaders[i];
        resp.addHeader(header.getName(), header.getValue());
    }

    // Transfer proxy response entity to the servlet response
    HttpEntity entity = response.getEntity();
    InputStream input = entity.getContent();
    OutputStream output = resp.getOutputStream();
    int b = input.read();
    while (b != -1) {
        output.write(b);
        b = input.read();
    }

    // Clean up
    input.close();
    output.close();
    httpclient.getConnectionManager().shutdown();
}

From source file:org.gnode.wda.server.ProxyServlet.java

License:asdf

@Override
@SuppressWarnings("unchecked")
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    // Create new client to perform the proxied request
    HttpClient httpclient = new DefaultHttpClient();

    // Determine final URL
    StringBuffer uri = new StringBuffer();
    uri.append(targetServer);// ww  w.  j a  va 2  s .  c o m
    // This is a very bad hack. In order to remove my proxy servlet-path, I have used a substring method.
    // Turns "/proxy/asdf" into "/asdf"
    uri.append(req.getRequestURI().substring(6));

    //    Add any supplied query strings
    String queryString = req.getQueryString();
    if (queryString != null) {
        uri.append("?" + queryString);
    }

    // Get HTTP method
    final String method = req.getMethod();
    // Create new HTTP request container
    HttpRequestBase request = null;

    // Get content length
    int contentLength = req.getContentLength();
    //    Unknown content length ...
    // if (contentLength == -1)
    // throw new ServletException("Cannot handle unknown content length");
    // If we don't have an entity body, things are quite simple
    if (contentLength < 1) {
        request = new HttpRequestBase() {
            public String getMethod() {
                return method;
            }
        };
    } else {
        // Prepare request
        HttpEntityEnclosingRequestBase tmpRequest = new HttpEntityEnclosingRequestBase() {
            public String getMethod() {
                return method;
            }
        };

        // Transfer entity body from the received request to the new request
        InputStreamEntity entity = new InputStreamEntity(req.getInputStream(), contentLength);
        tmpRequest.setEntity(entity);

        request = tmpRequest;
    }

    //    Set URI
    try {
        request.setURI(new URI(uri.toString()));
    } catch (URISyntaxException e) {
        throw new ServletException("URISyntaxException: " + e.getMessage());
    }

    //       Copy headers from old request to new request
    // @todo not sure how this handles multiple headers with the same name
    Enumeration<String> headers = req.getHeaderNames();
    while (headers.hasMoreElements()) {
        String headerName = headers.nextElement();
        String headerValue = req.getHeader(headerName);
        //       Skip Content-Length and Host
        String lowerHeader = headerName.toLowerCase();
        if (lowerHeader.equals("content-length") == false && lowerHeader.equals("host") == false) {
            //    System.out.println(headerName.toLowerCase() + ": " + headerValue);
            request.addHeader(headerName, headerValue);
        }
    }

    // Execute the request
    HttpResponse response = httpclient.execute(request);

    // Transfer status code to the response
    StatusLine status = response.getStatusLine();
    resp.setStatus(status.getStatusCode());
    // resp.setStatus(status.getStatusCode(), status.getReasonPhrase()); // This seems to be deprecated. Yes status message is "ambigous", but I don't approve

    // Transfer headers to the response
    Header[] responseHeaders = response.getAllHeaders();
    for (int i = 0; i < responseHeaders.length; i++) {
        Header header = responseHeaders[i];
        resp.addHeader(header.getName(), header.getValue());
    }

    //    Transfer proxy response entity to the servlet response
    HttpEntity entity = response.getEntity();

    if (entity == null)
        return;

    InputStream input = entity.getContent();
    OutputStream output = resp.getOutputStream();
    int b = input.read();
    while (b != -1) {
        output.write(b);
        b = input.read();
    }

    //       Clean up
    input.close();
    output.close();
    httpclient.getConnectionManager().shutdown();
}

From source file:com.dp.bigdata.taurus.web.servlet.CreateTaskServlet.java

@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    HttpClient httpclient = new DefaultHttpClient();
    // Determine final URL
    StringBuffer uri = new StringBuffer();

    if (req.getParameter("update") != null) {
        uri.append(targetUri).append("/").append(req.getParameter("update"));
    } else {//w w  w . j  a  va  2 s  . com
        uri.append(targetUri);
    }
    LOG.info("Access URI : " + uri.toString());
    // Get HTTP method
    final String method = req.getMethod();
    // Create new HTTP request container
    HttpRequestBase request = null;

    // Get content length
    int contentLength = req.getContentLength();
    // Unknown content length ...
    // if (contentLength == -1)
    // throw new ServletException("Cannot handle unknown content length");
    // If we don't have an entity body, things are quite simple
    if (contentLength < 1) {
        request = new HttpRequestBase() {
            public String getMethod() {
                return method;
            }
        };
    } else {
        // Prepare request
        HttpEntityEnclosingRequestBase tmpRequest = new HttpEntityEnclosingRequestBase() {
            public String getMethod() {
                return method;
            }
        };
        // Transfer entity body from the received request to the new request
        InputStreamEntity entity = new InputStreamEntity(req.getInputStream(), contentLength);
        tmpRequest.setEntity(entity);
        request = tmpRequest;
    }

    // Set URI
    try {
        request.setURI(new URI(uri.toString()));
    } catch (URISyntaxException e) {
        throw new ServletException("URISyntaxException: " + e.getMessage());
    }

    // Copy headers from old request to new request
    // @todo not sure how this handles multiple headers with the same name
    Enumeration<?> headers = req.getHeaderNames();
    while (headers.hasMoreElements()) {
        String headerName = (String) headers.nextElement();
        String headerValue = req.getHeader(headerName);
        //LOG.info("header: " + headerName + " value: " + headerValue);
        // Skip Content-Length and Host
        String lowerHeader = headerName.toLowerCase();
        if (lowerHeader.equals("content-type")) {
            request.addHeader(headerName, headerValue + ";charset=\"utf-8\"");
        } else if (!lowerHeader.equals("content-length") && !lowerHeader.equals("host")) {
            request.addHeader(headerName, headerValue);
        }
    }

    // Execute the request
    HttpResponse response = httpclient.execute(request);
    // Transfer status code to the response
    StatusLine status = response.getStatusLine();
    resp.setStatus(status.getStatusCode());

    // Transfer headers to the response
    Header[] responseHeaders = response.getAllHeaders();
    for (int i = 0; i < responseHeaders.length; i++) {
        Header header = responseHeaders[i];
        if (!header.getName().equals("Transfer-Encoding"))
            resp.addHeader(header.getName(), header.getValue());
    }

    // Transfer proxy response entity to the servlet response
    HttpEntity entity = response.getEntity();
    InputStream input = entity.getContent();
    OutputStream output = resp.getOutputStream();

    byte buffer[] = new byte[50];
    while (input.read(buffer) != -1) {
        output.write(buffer);
    }
    //        int b = input.read();
    //        while (b != -1) {
    //            output.write(b);
    //            b = input.read();
    //        }
    // Clean up
    input.close();
    output.close();
    httpclient.getConnectionManager().shutdown();
}

From source file:com.lonepulse.zombielink.request.UriProcessor.java

/**
 * <p>Accepts the {@link InvocationContext} along with the {@link HttpRequestBase} and forms 
 * the complete request URI by appending the request subpath to the root path defined on the 
 * endpoint. Any placeholders in the URI are replaced with their matching path parameters found 
 * in the request arguments annotated with @{@link PathParam}.</p>
 * /*from w ww  .j  a va  2 s. c  om*/
 * <p>Any processors which extract information from the <i>complete</i> request URI or those which 
 * seek to manipulate the URI should use this processor as a prerequisite.</p>
 * 
 * <p>See {@link AbstractRequestProcessor#process(InvocationContext, HttpRequestBase)}.</p>
 * 
 * @param context
 *          the {@link InvocationContext} used to discover root and subpath information  
 * <br><br>
 * @param request
 *          the {@link HttpRequestBase} whose URI will be initialized to the complete URI formulated 
 *          using the endpoint's root path, the request's subpath and any path parameters
 * <br><br>
  * @return the same instance of {@link HttpRequestBase} which was given for processing the URI
 * <br><br>
 * @throws RequestProcessorException
 *          if a URI failed to be created using the information found on the endpoint definition
 * <br><br>
 * @since 1.3.0
 */
@Override
protected HttpRequestBase process(InvocationContext context, HttpRequestBase request) {

    try {

        Endpoint endpoint = context.getEndpoint().getAnnotation(Endpoint.class);
        String path = endpoint.value() + Metadata.findPath(context.getRequest());

        List<Entry<PathParam, Object>> pathParams = Metadata.onParams(PathParam.class, context);

        for (Entry<PathParam, Object> entry : pathParams) {

            String name = entry.getKey().value();
            Object value = entry.getValue();

            if (!(value instanceof CharSequence)) {

                StringBuilder errorContext = new StringBuilder().append("Path parameters can only be of type ")
                        .append(CharSequence.class.getName())
                        .append(". Please consider implementing CharSequence ")
                        .append("and providing a meaningful toString() representation for the ")
                        .append("<name> of the path parameter. ");

                throw new RequestProcessorException(new IllegalArgumentException(errorContext.toString()));
            }

            path = path.replaceAll(Pattern.quote("{" + name + "}"), ((CharSequence) value).toString());
        }

        request.setURI(URI.create(path));

        return request;
    } catch (Exception e) {

        throw new RequestProcessorException(context, getClass(), e);
    }
}

From source file:com.jayway.restassured.internal.http.HTTPBuilder.java

/**
 * Create a {@link RequestConfigDelegate} from the given arguments, execute the
 * config closure, then pass the delegate to {@link #doRequest(RequestConfigDelegate)},
 * which actually executes the request.//  w  w w  .j a v a2 s . co  m
 */
protected Object doRequest(URI uri, Method method, Object contentType, Closure configClosure)
        throws ClientProtocolException, IOException {

    HttpRequestBase reqMethod;
    try {
        reqMethod = method.getRequestType().newInstance();
        // this exception should reasonably never occur:
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    reqMethod.setURI(uri);
    RequestConfigDelegate delegate = new RequestConfigDelegate(reqMethod, contentType,
            this.defaultRequestHeaders, this.defaultResponseHandlers);
    configClosure.setDelegate(delegate);
    configClosure.setResolveStrategy(Closure.DELEGATE_FIRST);
    configClosure.call(reqMethod);

    return this.doRequest(delegate);
}

From source file:org.fao.geonet.utils.AbstractHttpRequest.java

protected HttpRequestBase setupHttpMethod() throws IOException {
    String queryString = query;/*w w  w .  j  a  v  a2s.  com*/

    if (query == null || query.trim().isEmpty()) {
        StringBuilder b = new StringBuilder();

        for (NameValuePair alSimpleParam : alSimpleParams) {
            if (b.length() > 0) {
                b.append("&");
            }
            b.append(alSimpleParam.getName()).append('=').append(alSimpleParam.getValue());
        }
        if (b.length() > 0) {
            queryString = b.toString();
        }
    }

    if (host == null || protocol == null) {
        throw new IllegalStateException(
                String.format(getClass().getSimpleName() + " is not ready to be executed: \n\tprotocol: '%s' "
                        + "\n\tuserinfo: '%s'\n\thost: '%s' \n\tport: '%s' \n\taddress: '%s'\n\tquery '%s'"
                        + "\n\tfragment: '%s'", protocol, userInfo, host, port, address, query, fragment));
    }

    HttpRequestBase httpMethod;

    if (method == Method.GET) {
        HttpGet get = new HttpGet();

        get.addHeader("Accept", !useSOAP ? "application/xml" : "application/soap+xml");
        httpMethod = get;
    } else {
        HttpPost post = new HttpPost();

        if (!useSOAP) {
            postData = (postParams == null) ? "" : Xml.getString(new Document(postParams));
            HttpEntity entity = new StringEntity(postData, ContentType.create("application/xml", "UTF-8"));
            post.setEntity(entity);
        } else {
            postData = Xml.getString(new Document(soapEmbed(postParams)));
            HttpEntity entity = new StringEntity(postData, ContentType.create("application/xml", "UTF-8"));
            post.setEntity(entity);
        }

        httpMethod = post;
    }

    try {
        URI uri = new URI(protocol, userInfo, host, port, address, queryString, fragment);
        httpMethod.setURI(uri);
    } catch (URISyntaxException e) {
        throw new IOException(e);
    }

    final RequestConfig.Builder builder = RequestConfig.custom();
    builder.setAuthenticationEnabled((credentials != null) || (proxyCredentials != null));
    builder.setRedirectsEnabled(true);
    builder.setRelativeRedirectsAllowed(true);
    builder.setCircularRedirectsAllowed(true);
    builder.setMaxRedirects(3);
    builder.setCookieSpec(CookieSpecs.BROWSER_COMPATIBILITY);

    httpMethod.setConfig(builder.build());
    return httpMethod;
}