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

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

Introduction

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

Prototype

@Deprecated
    void setParams(HttpParams httpParams);

Source Link

Usage

From source file:spark.protocol.SparqlCall.java

/**
 * Executes a SPARQL HTTP protocol request for the given command, and returns the response.
 * @param command The SPARQL protocol command.
 * @return The HTTP response.//www. j  a v a2  s .c o  m
 */
static HttpResponse executeRequest(ProtocolCommand command, String mimeType) {
    HttpClient client = ((ProtocolConnection) command.getConnection()).getHttpClient();
    URL url = ((ProtocolDataSource) command.getConnection().getDataSource()).getUrl();
    HttpUriRequest req;

    try {
        String params = "query=" + encode(command.getCommand());
        String u = url.toString() + "?" + params;
        if (u.length() > QUERY_LIMIT) {
            // POST connection
            try {
                req = new HttpPost(url.toURI());
            } catch (URISyntaxException e) {
                throw new SparqlException("Endpoint <" + url + "> not in an acceptable format", e);
            }
            ((HttpPost) req).setEntity((HttpEntity) new StringEntity(params));
        } else {
            // GET connection
            req = new HttpGet(u);
        }

        if (command.getTimeout() != Command.NO_TIMEOUT) {
            HttpParams reqParams = new BasicHttpParams();
            HttpConnectionParams.setSoTimeout(reqParams, (int) (command.getTimeout() * 1000));
            req.setParams(reqParams);
        }

        // Add Accept and Content-Type (for POST'ed queries) headers to the request.
        addHeaders(req, mimeType);

        // There's a small chance the request could be aborted before it's even executed, we'll have to live with that.
        command.setRequest(req);

        //dump(client, req);
        HttpResponse response = client.execute(req);
        StatusLine status = response.getStatusLine();
        int code = status.getStatusCode();

        // TODO the client doesn't handle redirects for posts; should we do that here?

        if (code >= SUCCESS_MIN && code <= SUCCESS_MAX) {
            return response;
        } else {
            throw new SparqlException("Unexpected status code in server response: " + status.getReasonPhrase()
                    + "(" + code + ")");
        }
    } catch (UnsupportedEncodingException e) {
        throw new SparqlException("Unabled to encode data", e);
    } catch (ClientProtocolException cpe) {
        throw new SparqlException("Error in protocol", cpe);
    } catch (IOException e) {
        throw new SparqlException(e);
    }
}

From source file:net.sf.jsog.client.DefaultHttpClientImpl.java

/**
 * Executes a request and returns the resulting String.
 * @param request the request to execute.
 * @return the raw content string./*  ww w  .  ja v  a2  s  .c  o  m*/
 * @throws JsogClientException if the request fails.
 */
private synchronized String execute(final HttpUriRequest request) {
    request.setParams(params);

    // Set the request's headers
    for (Entry<String, String> header : headers.entrySet()) {
        request.setHeader(header.getKey(), header.getValue());
    }

    // Execute the request and get it's content
    HttpResponse response;
    String content;
    try {

        // Execute the request
        response = getClient().execute(request);

        // Get the response content
        content = EntityUtils.toString(response.getEntity(), charset);
    } catch (IOException e) {
        throw new JsogClientException("Get request failed.", e);
    }

    // Check the response code
    StatusLine sl = response.getStatusLine();
    if (sl.getStatusCode() != 200) {
        throw new Non200ResponseCodeException(sl.getStatusCode(), sl.getReasonPhrase(), content);
    }

    return content;
}

From source file:org.doctester.testbrowser.TestBrowserImpl.java

/**
 * Tells ApacheHttpClient whether to follow redirects. See also:
 * http://stackoverflow.com/questions/1519392/how-to-prevent-apache-http-client-from-following-a-redirect
 */// ww  w .  ja  v  a  2 s  . c  o m
private void setHandleRedirect(HttpUriRequest httpUriRequest, boolean handleRedirect) {

    HttpParams params = new BasicHttpParams();
    params.setParameter(HANDLE_REDIRECTS, handleRedirect);
    httpUriRequest.setParams(params);

}

From source file:com.subgraph.vega.internal.http.proxy.UriRequestCreator.java

public HttpUriRequest createUriRequest(HttpRequest request, boolean isSSL) throws HttpException {
    final URI uri = getUriForRequest(request, isSSL);
    final HttpUriRequest uriRequest;
    if (request instanceof HttpEntityEnclosingRequest) {
        HttpEntityEnclosingMutableRequest tmp = new HttpEntityEnclosingMutableRequest(
                request.getRequestLine().getMethod(), uri);
        tmp.setEntity(((HttpEntityEnclosingRequest) request).getEntity());
        uriRequest = tmp;/*from w w w .j  av a  2s.  com*/
    } else {
        uriRequest = new HttpMutableRequest(request.getRequestLine().getMethod(), uri);
    }
    uriRequest.setParams(request.getParams());
    uriRequest.setHeaders(request.getAllHeaders());
    return uriRequest;
}

From source file:org.teleal.cling.transport.impl.apache.StreamClientImpl.java

@Override
public StreamResponseMessage sendRequest(StreamRequestMessage requestMessage) {

    final UpnpRequest requestOperation = requestMessage.getOperation();
    log.fine("Preparing HTTP request message with method '" + requestOperation.getHttpMethodName() + "': "
            + requestMessage);//  w ww.j av a2 s. co  m

    try {

        // Create the right HTTP request
        HttpUriRequest httpRequest = createHttpRequest(requestMessage, requestOperation);
        HttpParams requestParams = getRequestParams(requestMessage);
        HttpConnectionParams.setConnectionTimeout(requestParams, 30000);
        HttpConnectionParams.setSoTimeout(requestParams, 30000);

        // Set all the headers on the request
        httpRequest.setParams(requestParams);
        HeaderUtil.add(httpRequest, requestMessage.getHeaders());

        log.fine("Sending HTTP request: " + httpRequest.getURI());
        return httpClient.execute(httpRequest, createResponseHandler());

    } catch (MethodNotSupportedException ex) {
        log.warning("Request aborted: " + ex.toString());
        return null;
    } catch (ClientProtocolException ex) {
        log.warning("HTTP protocol exception executing request: " + requestMessage);
        log.warning("Cause: " + Exceptions.unwrap(ex));
        return null;
    } catch (IOException ex) {
        log.fine("Client connection was aborted: " + ex.getMessage()); // Don't
        // log
        // stacktrace
        return null;
    }
}

From source file:com.subgraph.vega.internal.http.proxy.ProxyRequestHandler.java

private HttpUriRequest copyToUriRequest(HttpRequest request) throws ProtocolException {
    URI uri;/*from  w  w  w.j a v  a 2  s . c  o m*/
    try {
        uri = new URI(request.getRequestLine().getUri());
    } catch (URISyntaxException e) {
        throw new ProtocolException("Invalid URI: " + request.getRequestLine().getUri(), e);
    }
    // ensuring we have scheme and host also prevents the proxy from connecting back to itself
    if (uri.getScheme() == null) {
        throw new ProtocolException("No scheme in proxy request URI");
    }
    if (uri.getHost() == null) {
        throw new ProtocolException("No host in proxy request URI");
    }

    final HttpUriRequest uriRequest;
    if (request instanceof HttpEntityEnclosingRequest) {
        HttpEntityEnclosingMutableRequest tmp = new HttpEntityEnclosingMutableRequest(
                request.getRequestLine().getMethod(), uri);
        tmp.setEntity(copyEntity(((HttpEntityEnclosingRequest) request).getEntity()));
        uriRequest = tmp;
    } else {
        uriRequest = new HttpMutableRequest(request.getRequestLine().getMethod(), uri);
    }
    uriRequest.setParams(request.getParams());
    uriRequest.setHeaders(request.getAllHeaders());
    return uriRequest;
}

From source file:org.openrdf.http.client.SparqlSession.java

protected HttpResponse execute(HttpUriRequest method) throws IOException, OpenRDFException {
    boolean consume = true;
    method.setParams(params);
    HttpResponse response = httpClient.execute(method, httpContext);

    try {//w w w .  j  a v  a2s .c  om
        int httpCode = response.getStatusLine().getStatusCode();
        if (httpCode >= 200 && httpCode < 300 || httpCode == HttpURLConnection.HTTP_NOT_FOUND) {
            consume = false;
            return response; // everything OK, control flow can continue
        } else {
            switch (httpCode) {
            case HttpURLConnection.HTTP_UNAUTHORIZED: // 401
                throw new UnauthorizedException();
            case HttpURLConnection.HTTP_UNAVAILABLE: // 503
                throw new QueryInterruptedException();
            default:
                ErrorInfo errInfo = getErrorInfo(response);
                // Throw appropriate exception
                if (errInfo.getErrorType() == ErrorType.MALFORMED_DATA) {
                    throw new RDFParseException(errInfo.getErrorMessage());
                } else if (errInfo.getErrorType() == ErrorType.UNSUPPORTED_FILE_FORMAT) {
                    throw new UnsupportedRDFormatException(errInfo.getErrorMessage());
                } else if (errInfo.getErrorType() == ErrorType.MALFORMED_QUERY) {
                    throw new MalformedQueryException(errInfo.getErrorMessage());
                } else if (errInfo.getErrorType() == ErrorType.UNSUPPORTED_QUERY_LANGUAGE) {
                    throw new UnsupportedQueryLanguageException(errInfo.getErrorMessage());
                } else {
                    throw new RepositoryException(errInfo.toString());
                }
            }
        }
    } finally {
        if (consume) {
            EntityUtils.consumeQuietly(response.getEntity());
        }
    }
}

From source file:org.eclipse.rdf4j.http.client.SPARQLProtocolSession.java

protected HttpResponse execute(HttpUriRequest method) throws IOException, RDF4JException {
    boolean consume = true;
    if (params != null) {
        method.setParams(params);
    }/*from www. ja v a 2  s .  c  o m*/
    HttpResponse response = httpClient.execute(method, httpContext);

    try {
        int httpCode = response.getStatusLine().getStatusCode();
        if (httpCode >= 200 && httpCode < 300 || httpCode == HttpURLConnection.HTTP_NOT_FOUND) {
            consume = false;
            return response; // everything OK, control flow can continue
        } else {
            switch (httpCode) {
            case HttpURLConnection.HTTP_UNAUTHORIZED: // 401
                throw new UnauthorizedException();
            case HttpURLConnection.HTTP_UNAVAILABLE: // 503
                throw new QueryInterruptedException();
            default:
                ErrorInfo errInfo = getErrorInfo(response);
                // Throw appropriate exception
                if (errInfo.getErrorType() == ErrorType.MALFORMED_DATA) {
                    throw new RDFParseException(errInfo.getErrorMessage());
                } else if (errInfo.getErrorType() == ErrorType.UNSUPPORTED_FILE_FORMAT) {
                    throw new UnsupportedRDFormatException(errInfo.getErrorMessage());
                } else if (errInfo.getErrorType() == ErrorType.MALFORMED_QUERY) {
                    throw new MalformedQueryException(errInfo.getErrorMessage());
                } else if (errInfo.getErrorType() == ErrorType.UNSUPPORTED_QUERY_LANGUAGE) {
                    throw new UnsupportedQueryLanguageException(errInfo.getErrorMessage());
                } else if (errInfo.toString().length() > 0) {
                    throw new RepositoryException(errInfo.toString());
                } else {
                    throw new RepositoryException(response.getStatusLine().getReasonPhrase());
                }
            }
        }
    } finally {
        if (consume) {
            EntityUtils.consumeQuietly(response.getEntity());
        }
    }
}

From source file:org.fourthline.cling.transport.impl.apache.StreamClientImpl.java

@Override
protected HttpUriRequest createRequest(StreamRequestMessage requestMessage) {
    UpnpRequest requestOperation = requestMessage.getOperation();
    HttpUriRequest request;
    switch (requestOperation.getMethod()) {
    case GET:/*from  w  ww. ja va 2 s.  c o  m*/
        request = new HttpGet(requestOperation.getURI());
        break;
    case SUBSCRIBE:
        request = new HttpGet(requestOperation.getURI()) {
            @Override
            public String getMethod() {
                return UpnpRequest.Method.SUBSCRIBE.getHttpName();
            }
        };
        break;
    case UNSUBSCRIBE:
        request = new HttpGet(requestOperation.getURI()) {
            @Override
            public String getMethod() {
                return UpnpRequest.Method.UNSUBSCRIBE.getHttpName();
            }
        };
        break;
    case POST:
        HttpEntityEnclosingRequest post = new HttpPost(requestOperation.getURI());
        post.setEntity(createHttpRequestEntity(requestMessage));
        request = (HttpUriRequest) post; // Fantastic API
        break;
    case NOTIFY:
        HttpEntityEnclosingRequest notify = new HttpPost(requestOperation.getURI()) {
            @Override
            public String getMethod() {
                return UpnpRequest.Method.NOTIFY.getHttpName();
            }
        };
        notify.setEntity(createHttpRequestEntity(requestMessage));
        request = (HttpUriRequest) notify; // Fantastic API
        break;
    default:
        throw new RuntimeException("Unknown HTTP method: " + requestOperation.getHttpMethodName());
    }

    // Headers
    request.setParams(getRequestParams(requestMessage));
    HeaderUtil.add(request, requestMessage.getHeaders());

    return request;
}

From source file:com.amazonaws.http.ApacheHttpClient.java

private HttpUriRequest createHttpRequest(HttpRequest request) {
    HttpUriRequest httpRequest;
    String method = request.getMethod();
    if (method.equals("POST")) {
        HttpPost postRequest = new HttpPost(request.getUri());
        if (request.getContent() != null) {
            postRequest.setEntity(new InputStreamEntity(request.getContent(), request.getContentLength()));
        }//from w w w  .j  a va  2s. c o m
        httpRequest = postRequest;
    } else if (method.equals("GET")) {
        httpRequest = new HttpGet(request.getUri());
    } else if (method.equals("PUT")) {
        HttpPut putRequest = new HttpPut(request.getUri());
        if (request.getContent() != null) {
            putRequest.setEntity(new InputStreamEntity(request.getContent(), request.getContentLength()));
        }
        httpRequest = putRequest;
    } else if (method.equals("DELETE")) {
        httpRequest = new HttpDelete(request.getUri());
    } else if (method.equals("HEAD")) {
        httpRequest = new HttpHead(request.getUri());
    } else {
        throw new UnsupportedOperationException("Unsupported method: " + method);
    }

    if (request.getHeaders() != null && !request.getHeaders().isEmpty()) {
        for (Map.Entry<String, String> header : request.getHeaders().entrySet()) {
            String key = header.getKey();
            /*
             * HttpClient4 fills in the Content-Length header and complains
             * if it's already present, so we skip it here. We also skip the
             * Host header to avoid sending it twice, which will interfere
             * with some signing schemes.
             */
            if (key.equals(HttpHeader.CONTENT_LENGTH) || key.equals(HttpHeader.HOST)) {
                continue;
            }
            httpRequest.addHeader(header.getKey(), header.getValue());
        }
    }

    // disable redirect
    if (params == null) {
        params = new BasicHttpParams();
        params.setParameter(ClientPNames.HANDLE_REDIRECTS, false);
    }
    httpRequest.setParams(params);
    return httpRequest;
}