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:org.nextlets.erc.defaults.http.ERCHttpInvokerImpl.java

protected URI createUri(ERCConfiguration configuration, String methodEndpoint, HttpRequestBase req,
        String contentType, Map<String, String> params) {
    String suri;//from   w w w.  ja v a  2s.  c  o m
    try {
        suri = ERCUtils.buildUrlAndParameters(configuration, methodEndpoint, req, contentType, params);
        log.debug("URI: {}", suri);
    } catch (UnsupportedEncodingException ex) {
        throw new ERCClientException(ex.getMessage(), ex);
    }
    URI uri = null;
    try {
        uri = new URI(suri);
        req.setURI(uri);
    } catch (URISyntaxException ex) {
        throw new ERCClientException("Could not make URI from: " + suri, ex);
    }
    return uri;
}

From source file:com.rackspacecloud.client.service_registry.clients.BaseClient.java

protected ClientResponse performRequest(String path, List<NameValuePair> params, HttpRequestBase method,
        boolean parseAsJson, Type responseType, boolean reAuthenticate, int retryCount) throws Exception {
    int statusCode;

    this.authClient.refreshToken(reAuthenticate);

    String url = (this.apiUrl + "/" + this.authClient.getAuthToken().getTenant().get("id") + path);

    if (params != null) {
        url += "?" + URLEncodedUtils.format(params, "UTF-8");
    }// w ww  .j ava2s  .co m

    method.setURI(new URI(url));
    method.setHeader("User-Agent", Client.VERSION);
    method.setHeader("X-Auth-Token", this.authClient.getAuthToken().getId());

    HttpResponse response = this.client.execute(method);
    statusCode = response.getStatusLine().getStatusCode();

    if ((statusCode == 401) && (retryCount < MAX_401_RETRIES)) {
        retryCount++;
        logger.info("API server returned 401, re-authenticating and re-trying the request");
        return this.performRequest(path, params, method, parseAsJson, responseType, true, retryCount);
    }

    return new ClientResponse(response, parseAsJson, responseType);
}

From source file:edu.cmu.sei.ams.cloudlet.impl.CloudletCommandExecutorImpl.java

/**
 * Compiles a command into an unencrypted API call.
 * @param cmd The object with the command details.
 * @return A HttpRequestBase request containing an URL to call the API for the given command.
 *///from w  ww  .j  a  v  a2 s.c om
@SuppressWarnings("deprecation")
protected HttpRequestBase compileOpenRequest(CloudletCommand cmd, String ipAddress, int port)
        throws URISyntaxException {

    String apiCommandUrl = String.format("http://%s:%d/api%s", ipAddress, port, cmd.getPath());

    // Create the URL string for the params.
    String args = null;
    for (String key : cmd.getArgs().keySet()) {
        if (args == null)
            args = "?";
        else
            args += "&";
        args += key + "=" + URLEncoder.encode(cmd.getArgs().get(key));
    }

    // Merge the URL plus the params string.
    if (args != null)
        apiCommandUrl += args;
    log.info("Compiled command: " + apiCommandUrl);

    // Set up the request based on the comand and the selected method.
    HttpRequestBase request;
    switch (cmd.getMethod()) {
    case GET:
        request = new HttpGet();
        break;
    case PUT:
        request = new HttpPut();
        break;
    case POST:
        request = new HttpPost();
        break;
    default:
        request = new HttpGet();
        break;
    }
    request.setURI(new URI(apiCommandUrl));

    return request;
}

From source file:com.appdynamics.demo.gasp.service.RESTIntentService.java

@Override
protected void onHandleIntent(Intent intent) {
    Uri action = intent.getData();/*from  w w  w.j a va  2  s  .  co  m*/
    Bundle extras = intent.getExtras();

    if (extras == null || action == null || !extras.containsKey(EXTRA_RESULT_RECEIVER)) {
        Log.e(TAG, "You did not pass extras or data with the Intent.");
        return;
    }

    int verb = extras.getInt(EXTRA_HTTP_VERB, GET);
    Bundle params = extras.getParcelable(EXTRA_PARAMS);
    Bundle headers = extras.getParcelable(EXTRA_HEADERS);
    ResultReceiver receiver = extras.getParcelable(EXTRA_RESULT_RECEIVER);

    try {
        HttpRequestBase request = null;

        // Get query params from Bundle and build URL
        switch (verb) {
        case GET: {
            request = new HttpGet();
            attachUriWithQuery(request, action, params);
        }
            break;

        case DELETE: {
            request = new HttpDelete();
            attachUriWithQuery(request, action, params);
        }
            break;

        case POST: {
            request = new HttpPost();
            request.setURI(new URI(action.toString()));

            HttpPost postRequest = (HttpPost) request;

            if (params != null) {
                UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(paramsToList(params));
                postRequest.setEntity(formEntity);
            }
        }
            break;

        case PUT: {
            request = new HttpPut();
            request.setURI(new URI(action.toString()));

            HttpPut putRequest = (HttpPut) request;

            if (params != null) {
                UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(paramsToList(params));
                putRequest.setEntity(formEntity);
            }
        }
            break;
        }

        // Get Headers from Bundle
        for (BasicNameValuePair header : paramsToList(headers)) {
            request.setHeader(header.getName(), header.getValue());
        }

        if (request != null) {
            HttpClient client = new DefaultHttpClient();

            Log.d(TAG, "Executing request: " + verbToString(verb) + ": " + action.toString());

            HttpResponse response = client.execute(request);

            HttpEntity responseEntity = response.getEntity();
            StatusLine responseStatus = response.getStatusLine();
            int statusCode = responseStatus != null ? responseStatus.getStatusCode() : 0;

            if ((responseEntity != null) && (responseStatus.getStatusCode() == 200)) {
                Bundle resultData = new Bundle();
                resultData.putString(REST_RESULT, EntityUtils.toString(responseEntity));
                receiver.send(statusCode, resultData);
            } else {
                receiver.send(statusCode, null);
            }
        }
    } catch (URISyntaxException e) {
        Log.e(TAG, "URI syntax was incorrect. " + verbToString(verb) + ": " + action.toString(), e);
        receiver.send(0, null);
    } catch (UnsupportedEncodingException e) {
        Log.e(TAG, "A UrlEncodedFormEntity was created with an unsupported encoding.", e);
        receiver.send(0, null);
    } catch (ClientProtocolException e) {
        Log.e(TAG, "There was a problem when sending the request.", e);
        receiver.send(0, null);
    } catch (IOException e) {
        Log.e(TAG, "There was a problem when sending the request.", e);
        receiver.send(0, null);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:net.netheos.pcsapi.providers.hubic.Swift.java

private void configureSession(HttpRequestBase request, String format) {
    request.addHeader("X-Auth-token", authToken);
    if (format != null) {
        try {//from   ww  w. j a  v a 2 s.c  o m
            URI uri = request.getURI();
            if (uri.getRawQuery() != null) {
                request.setURI(URI.create(uri + "&format=" + URLEncoder.encode(format, "UTF-8")));
            } else {
                request.setURI(URI.create(uri + "?format=" + URLEncoder.encode(format, "UTF-8")));
            }

        } catch (UnsupportedEncodingException ex) {
            throw new UnsupportedOperationException("Error setting the request format", ex);
        }
    }
}

From source file:com.cloudbees.gasp.service.RESTService.java

@Override
protected void onHandleIntent(Intent intent) {
    // When an intent is received by this Service, this method
    // is called on a new thread.

    Uri action = intent.getData();//from  ww  w  . ja v a  2  s  .  c  o  m
    Bundle extras = intent.getExtras();

    if (extras == null || action == null || !extras.containsKey(EXTRA_RESULT_RECEIVER)) {
        // Extras contain our ResultReceiver and data is our REST action.  
        // So, without these components we can't do anything useful.
        Log.e(TAG, "You did not pass extras or data with the Intent.");

        return;
    }

    // We default to GET if no verb was specified.
    int verb = extras.getInt(EXTRA_HTTP_VERB, GET);
    Bundle params = extras.getParcelable(EXTRA_PARAMS);
    ResultReceiver receiver = extras.getParcelable(EXTRA_RESULT_RECEIVER);

    try {
        // Here we define our base request object which we will
        // send to our REST service via HttpClient.
        HttpRequestBase request = null;

        // Let's build our request based on the HTTP verb we were
        // given.
        switch (verb) {
        case GET: {
            request = new HttpGet();
            attachUriWithQuery(request, action, params);
        }
            break;

        case DELETE: {
            request = new HttpDelete();
            attachUriWithQuery(request, action, params);
        }
            break;

        case POST: {
            request = new HttpPost();
            request.setURI(new URI(action.toString()));

            // Attach form entity if necessary. Note: some REST APIs
            // require you to POST JSON. This is easy to do, simply use
            // postRequest.setHeader('Content-Type', 'application/json')
            // and StringEntity instead. Same thing for the PUT case 
            // below.
            HttpPost postRequest = (HttpPost) request;

            if (params != null) {
                UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(paramsToList(params));
                postRequest.setEntity(formEntity);
            }
        }
            break;

        case PUT: {
            request = new HttpPut();
            request.setURI(new URI(action.toString()));

            // Attach form entity if necessary.
            HttpPut putRequest = (HttpPut) request;

            if (params != null) {
                UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(paramsToList(params));
                putRequest.setEntity(formEntity);
            }
        }
            break;
        }

        if (request != null) {
            HttpClient client = new DefaultHttpClient();

            // Let's send some useful debug information so we can monitor things
            // in LogCat.
            Log.d(TAG, "Executing request: " + verbToString(verb) + ": " + action.toString());

            // Finally, we send our request using HTTP. This is the synchronous
            // long operation that we need to run on this thread.
            HttpResponse response = client.execute(request);

            HttpEntity responseEntity = response.getEntity();
            StatusLine responseStatus = response.getStatusLine();
            int statusCode = responseStatus != null ? responseStatus.getStatusCode() : 0;

            // Our ResultReceiver allows us to communicate back the results to the caller. This
            // class has a method named send() that can send back a code and a Bundle
            // of data. ResultReceiver and IntentService abstract away all the IPC code
            // we would need to write to normally make this work.
            if (responseEntity != null) {
                Bundle resultData = new Bundle();
                resultData.putString(REST_RESULT, EntityUtils.toString(responseEntity));
                receiver.send(statusCode, resultData);
            } else {
                receiver.send(statusCode, null);
            }
        }
    } catch (URISyntaxException e) {
        Log.e(TAG, "URI syntax was incorrect. " + verbToString(verb) + ": " + action.toString(), e);
        receiver.send(0, null);
    } catch (UnsupportedEncodingException e) {
        Log.e(TAG, "A UrlEncodedFormEntity was created with an unsupported encoding.", e);
        receiver.send(0, null);
    } catch (ClientProtocolException e) {
        Log.e(TAG, "There was a problem when sending the request.", e);
        receiver.send(0, null);
    } catch (IOException e) {
        Log.e(TAG, "There was a problem when sending the request.", e);
        receiver.send(0, null);
    }
}

From source file:org.apache.wink.client.internal.handlers.httpclient.ApacheHttpClientConnectionHandler.java

private HttpRequestBase setupHttpRequest(ClientRequest request, HttpClient client, EntityWriter entityWriter) {
    URI uri = request.getURI();//  w  w w  . j a  v  a 2  s . com
    String method = request.getMethod();
    HttpRequestBase httpRequest = null;
    if (entityWriter == null) {
        GenericHttpRequestBase entityRequest = new GenericHttpRequestBase(method);
        httpRequest = entityRequest;
    } else {
        // create a new request with the specified method
        HttpEntityEnclosingRequestBase entityRequest = new GenericHttpEntityEnclosingRequestBase(method);
        entityRequest.setEntity(entityWriter);
        httpRequest = entityRequest;
    }
    // set the uri
    httpRequest.setURI(uri);
    // add all headers
    MultivaluedMap<String, String> headers = request.getHeaders();
    for (String header : headers.keySet()) {
        List<String> values = headers.get(header);
        for (String value : values) {
            if (value != null) {
                httpRequest.addHeader(header, value);
            }
        }
    }
    return httpRequest;
}

From source file:com.ibm.watson.developer_cloud.service.WatsonService.java

/**
 * Execute the Http request.//from   w w w.j  av  a  2s  .c o m
 * 
 * @param request
 *            the http request
 * 
 * @return the http response
 */
protected HttpResponse execute(HttpRequestBase request) {

    setAuthentication(request);

    if (getEndPoint() == null)
        throw new IllegalArgumentException("service endpoint was not specified");

    if (!request.containsHeader(ACCEPT)) {
        request.addHeader(ACCEPT, getDefaultContentType());
    }

    // from /v1/foo/bar to https://host:port/api/v1/foo/bar
    if (!request.getURI().isAbsolute()) {
        request.setURI(buildRequestURI(request));
    }
    HttpResponse response;

    //HttpHost proxy=new HttpHost("10.100.1.124",3128);

    log.log(Level.FINEST, "Request to: " + request.getURI());
    try {
        response = getHttpClient().execute(request);
        //ConnRouteParams.setDefaultProxy(response.getParams(),proxy);
    } catch (ClientProtocolException e) {
        log.log(Level.SEVERE, "ClientProtocolException", e);
        throw new RuntimeException(e);
    } catch (IOException e) {
        log.log(Level.SEVERE, "IOException", e);
        throw new RuntimeException(e);
    }

    final int status = response.getStatusLine().getStatusCode();
    log.log(Level.FINEST, "Response HTTP Status: " + status);

    if (status >= 200 && status < 300)
        return response;

    // There was a Client Error 4xx or a Server Error 5xx
    // Get the error message and create the exception
    String error = getErrorMessage(response);
    log.log(Level.SEVERE, "HTTP Status: " + status + ", message: " + error);

    switch (status) {
    case HttpStatus.SC_BAD_REQUEST: // HTTP 400
        throw new BadRequestException(error != null ? error : "Bad Request");
    case HttpStatus.SC_UNAUTHORIZED: // HTTP 401
        throw new UnauthorizedException("Unauthorized: Access is denied due to invalid credentials");
    case HttpStatus.SC_FORBIDDEN: // HTTP 403
        throw new ForbiddenException(error != null ? error : "Forbidden: Service refuse the request");
    case HttpStatus.SC_NOT_FOUND: // HTTP 404
        throw new NotFoundException(error != null ? error : "Not found");
    case HttpStatus.SC_NOT_ACCEPTABLE: // HTTP 406
        throw new ForbiddenException(error != null ? error : "Forbidden: Service refuse the request");
    case HttpStatus.SC_REQUEST_TOO_LONG: // HTTP 413
        throw new RequestTooLargeException(error != null ? error
                : "Request too large: The request entity is larger than the server is able to process");
    case HttpStatus.SC_UNSUPPORTED_MEDIA_TYPE: // HTTP 415
        throw new UnsupportedException(error != null ? error
                : "Unsupported MIME type: The request entity has a media type which the server or resource does not support");
    case 429: // HTTP 429
        throw new TooManyRequestsException(error != null ? error : "Too many requests");
    case HttpStatus.SC_INTERNAL_SERVER_ERROR: // HTTP 500
        throw new InternalServerErrorException(error != null ? error : "Internal Server Error");
    case HttpStatus.SC_SERVICE_UNAVAILABLE: // HTTP 503
        throw new ServiceUnavailableException(error != null ? error : "Service Unavailable");
    default: // other errors
        throw new ServiceResponseException(status, error);
    }
}

From source file:com.cloudbees.gasp.loader.RESTLoader.java

@Override
public RESTResponse loadInBackground() {
    try {//from   w  w w.  j av  a2 s  .c o  m
        // At the very least we always need an action.
        if (mAction == null) {
            Log.e(TAG, "You did not define an action. REST call canceled.");
            return new RESTResponse(); // We send an empty response back. The LoaderCallbacks<RESTResponse>
                                       // implementation will always need to check the RESTResponse
                                       // and handle error cases like this.
        }

        // Here we define our base request object which we will
        // send to our REST service via HttpClient.
        HttpRequestBase request = null;

        // Let's build our request based on the HTTP verb we were
        // given.
        switch (mVerb) {
        case GET: {
            request = new HttpGet();
            attachUriWithQuery(request, mAction, mParams);
        }
            break;

        case DELETE: {
            request = new HttpDelete();
            attachUriWithQuery(request, mAction, mParams);
        }
            break;

        case POST: {
            request = new HttpPost();
            request.setURI(new URI(mAction.toString()));

            // Attach form entity if necessary. Note: some REST APIs
            // require you to POST JSON. This is easy to do, simply use
            // postRequest.setHeader('Content-Type', 'application/json')
            // and StringEntity instead. Same thing for the PUT case 
            // below.
            HttpPost postRequest = (HttpPost) request;

            if (mParams != null) {
                UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(paramsToList(mParams));
                postRequest.setEntity(formEntity);
            }
        }
            break;

        case PUT: {
            request = new HttpPut();
            request.setURI(new URI(mAction.toString()));

            // Attach form entity if necessary.
            HttpPut putRequest = (HttpPut) request;

            if (mParams != null) {
                UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(paramsToList(mParams));
                putRequest.setEntity(formEntity);
            }
        }
            break;
        }

        if (request != null) {
            HttpClient client = new DefaultHttpClient();

            // Let's send some useful debug information so we can monitor things
            // in LogCat.
            Log.d(TAG, "Executing request: " + verbToString(mVerb) + ": " + mAction.toString());

            // Finally, we send our request using HTTP. This is the synchronous
            // long operation that we need to run on this Loader's thread.
            HttpResponse response = client.execute(request);

            HttpEntity responseEntity = response.getEntity();
            StatusLine responseStatus = response.getStatusLine();
            int statusCode = responseStatus != null ? responseStatus.getStatusCode() : 0;

            // Here we create our response and send it back to the LoaderCallbacks<RESTResponse> implementation.
            RESTResponse restResponse = new RESTResponse(
                    responseEntity != null ? EntityUtils.toString(responseEntity) : null, statusCode);
            return restResponse;
        }

        // Request was null if we get here, so let's just send our empty RESTResponse like usual.
        return new RESTResponse();
    } catch (URISyntaxException e) {
        Log.e(TAG, "URI syntax was incorrect. " + verbToString(mVerb) + ": " + mAction.toString(), e);
        return new RESTResponse();
    } catch (UnsupportedEncodingException e) {
        Log.e(TAG, "A UrlEncodedFormEntity was created with an unsupported encoding.", e);
        return new RESTResponse();
    } catch (ClientProtocolException e) {
        Log.e(TAG, "There was a problem when sending the request.", e);
        return new RESTResponse();
    } catch (IOException e) {
        Log.e(TAG, "There was a problem when sending the request.", e);
        return new RESTResponse();
    }
}

From source file:net.tirasa.wink.client.asynchttpclient.ApacheHttpAsyncClientConnectionHandler.java

private HttpRequestBase setupHttpRequest(ClientRequest request,
        ApacheHttpAsyncClientConnectionHandler.EntityWriter entityWriter) {

    URI uri = request.getURI();/*from w  ww.ja va  2 s.  c o  m*/
    String method = request.getMethod();
    HttpRequestBase httpRequest;
    if (entityWriter == null) {
        GenericHttpRequestBase entityRequest = new GenericHttpRequestBase(method);
        httpRequest = entityRequest;
    } else {
        // create a new request with the specified method
        HttpEntityEnclosingRequestBase entityRequest = new ApacheHttpAsyncClientConnectionHandler.GenericHttpEntityEnclosingRequestBase(
                method);
        entityRequest.setEntity(entityWriter);
        httpRequest = entityRequest;
    }
    // set the uri
    httpRequest.setURI(uri);
    // add all headers
    MultivaluedMap<String, String> headers = request.getHeaders();
    for (String header : headers.keySet()) {
        List<String> values = headers.get(header);
        for (String value : values) {
            if (value != null) {
                httpRequest.addHeader(header, value);
            }
        }
    }
    return httpRequest;
}