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.kolich.havalo.client.service.HavaloAbstractService.java

/**
 * Prepares and signs the request./*w ww  .  ja  v  a2 s  . c o  m*/
 * @param request the request object
 * @return the {@link HavaloHttpResponse} response assuming the
 * request was successful. If the request was not successful, then
 * an exception will be thrown.
 */
protected final void signRequest(final HttpRequestBase request) {
    checkNotNull(request, "Request cannot be null!");
    // Compute the final endpoint for the request and set it.
    request.setURI(getFinalEndpoint(request));
    // Sign the request using an appropriate request signer.      
    signer_.signHttpRequest(request);
}

From source file:com.redwoodsystems.android.apps.loaders.ScenesAPILoader.java

@Override
public RESTResponse loadInBackground() {
    try {/*from w  ww  .j a v a 2s.  c  om*/
        // 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.
        }

        //make sure we always have a location
        if (mLocation == null) {
            Log.e(TAG, "No location found. REST call canceled.");
            return new RESTResponse();
        }

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

        request = new HttpGet();
        request.setURI(new URI(mAction.toString()));

        HttpGet getRequest = (HttpGet) request;

        getRequest.setHeader("Accept", "application/json");
        getRequest.setHeader("Content-type", "application/json");

        if (request != null) {
            //HttpClient client = new DefaultHttpClient();
            HttpClient client = HttpUtil.getNewHttpClient();

            //BASIC Authentication
            HttpUtil.setBasicAuthCredentials(client, mUserName, mPassword);

            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;
            String respString = "";
            RESTResponse restResponse = null;

            // Here we create our response and send it back to the LoaderCallbacks<RESTResponse> implementation.

            if (responseEntity != null) {
                respString = EntityUtils.toString(responseEntity);
                restResponse = new RESTResponse(respString, statusCode);
            } else {
                restResponse = new RESTResponse(null, statusCode);
            }

            Log.d(TAG, respString);
            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:com.twinsoft.convertigo.beans.transactions.couchdb.CustomTransaction.java

@Override
protected Object invoke() throws Exception {
    CouchClient provider = getCouchClient();

    String evaluatedUrl = eUrl == null ? "" : eUrl.toString();

    if (!evaluatedUrl.startsWith("/")) {
        evaluatedUrl = '/' + evaluatedUrl;
    }/*from   w  w w .j  a v a2 s .  c  om*/

    String db = getConnector().getDatabaseName();
    URI uri = new URI(provider.getDatabaseUrl(db) + evaluatedUrl);
    Engine.logBeans.debug("(CustomTransaction) CouchDb request uri: " + uri.toString());

    String jsonString = null;
    Object jsond = toJson(eData);
    if (jsond != null) {
        JSONObject jsonData;

        if (jsond instanceof JSONObject) { // comes from a complex variable
            jsonData = (JSONObject) jsond;
        } else {
            jsonData = new JSONObject();
            jsonData.put("data", jsond);
        }
        jsonString = jsonData.toString();
        Engine.logBeans.debug("(CustomTransaction) CouchDb request data: " + jsonString);
    }

    HttpRequestBase request = getHttpVerb().newInstance();

    if (request == null) {
        throw new EngineException("Unsupported HTTP method");
    }

    request.setURI(uri);

    if (jsonString != null && request instanceof HttpEntityEnclosingRequest) {
        provider.setJsonEntity((HttpEntityEnclosingRequest) request, jsonString);
    }

    return provider.execute(request);
}

From source file:com.redwoodsystems.android.apps.loaders.LocationsAPILoader.java

@Override
public RESTResponse loadInBackground() {
    try {//www . j av  a 2s.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;

        request = new HttpPost();
        request.setURI(new URI(mAction.toString()));

        HttpPost postRequest = (HttpPost) request;

        postRequest.setHeader("Accept", "application/json");
        postRequest.setHeader("Content-type", "application/json");
        postRequest.setEntity(new StringEntity(jsonReqStr));
        //postRequest.addHeader("Authorization",getAuthHeader());   

        if (request != null) {

            //get HttpClient with SSL parameters
            HttpClient client = HttpUtil.getNewHttpClient();

            //BASIC Authentication
            HttpUtil.setBasicAuthCredentials(client, this.mUserName, this.mPassword);

            Log.d(TAG, "Executing request: " + verbToString(mVerb) + ": " + mAction.toString());
            Log.d(TAG, jsonReqStr);

            //Validate JSON
            //HttpUtil.validateJSONString(jsonReqStr);

            // 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;
            String respString = "";
            RESTResponse restResponse = null;

            // Here we create our response and send it back to the LoaderCallbacks<RESTResponse> implementation.

            if (responseEntity != null) {
                respString = EntityUtils.toString(responseEntity);
                restResponse = new RESTResponse(respString, statusCode);
            } else {
                restResponse = new RESTResponse(null, statusCode);
            }

            Log.d(TAG, respString);
            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:com.redwoodsystems.android.apps.loaders.SceneUpdateAPILoader.java

@Override
public RESTResponse loadInBackground() {
    try {//from w w w. ja  va 2s . 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.
        }

        if (mLocationItem == null) {
            Log.e(TAG, "No location found. REST call canceled.");
            return new RESTResponse();
        }

        String jsonReqStr = String.format(JSON_REQ_TEMPLATE, mLocationItem.getLocationId(), mActivateSceneName);

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

        request = new HttpPost();
        request.setURI(new URI(mAction.toString()));

        HttpPost postRequest = (HttpPost) request;

        postRequest.setHeader("Accept", "application/json");
        postRequest.setHeader("Content-type", "application/json");
        postRequest.setEntity(new StringEntity(jsonReqStr));

        if (request != null) {

            //get HttpClient with SSL parameters
            HttpClient client = HttpUtil.getNewHttpClient();

            //BASIC Authentication
            HttpUtil.setBasicAuthCredentials(client, this.mUserName, this.mPassword);

            Log.d(TAG, "Executing request: " + verbToString(mVerb) + ": " + mAction.toString());
            Log.d(TAG, jsonReqStr);

            //Validate JSON
            HttpUtil.validateJSONString(jsonReqStr);

            // 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;
            String respString = "";
            RESTResponse restResponse = null;

            // Here we create our response and send it back to the LoaderCallbacks<RESTResponse> implementation.

            if (responseEntity != null) {
                respString = EntityUtils.toString(responseEntity);
                restResponse = new RESTResponse(respString, statusCode);
            } else {
                restResponse = new RESTResponse(null, statusCode);
            }

            Log.d(TAG, respString);
            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:com.trellmor.berrymotes.sync.EmoteDownloader.java

private String[] getSubreddits() throws IOException, URISyntaxException {
    Log.debug("Downloading emote list");
    HttpRequestBase request = new HttpGet();
    request.setURI(new URI(HOST + SUBREDDITS));

    this.checkCanDownload();
    HttpResponse response = mHttpClient.execute(request);
    switch (response.getStatusLine().getStatusCode()) {
    case 200:/*from  ww w  . ja v  a  2  s.  co m*/
        Log.debug(SUBREDDITS + " loaded");

        HttpEntity entity = response.getEntity();
        if (entity != null) {
            InputStream is = entity.getContent();
            GZIPInputStream zis = null;
            Reader isr = null;
            try {
                zis = new GZIPInputStream(is);
                isr = new InputStreamReader(zis, "UTF-8");

                Gson gson = new Gson();
                String[] subreddits = gson.fromJson(isr, String[].class);
                return subreddits;
            } finally {
                StreamUtils.closeStream(isr);
                StreamUtils.closeStream(zis);
                StreamUtils.closeStream(is);
            }
        }
        break;
    default:
        throw new IOException("Unexpected HTTP response: " + response.getStatusLine().getReasonPhrase());
    }
    return null;
}

From source file:gmusic.api.comm.ApacheConnector.java

private HttpRequestBase adjustAddress(URI address, HttpRequestBase request)
        throws MalformedURLException, URISyntaxException {
    if (address.toString().startsWith(HTTPS_PLAY_GOOGLE_COM_MUSIC_SERVICES)) {
        address = new URI(address.toURL() + String.format(COOKIE_FORMAT, getCookieValue("xt")));
    }/*from   www .  ja  v  a 2  s . c o  m*/

    request.setURI(address);

    if (authorizationToken != null) {
        request.addHeader(GOOGLE_LOGIN_AUTH_KEY, String.format(GOOGLE_LOGIN_AUTH_VALUE, authorizationToken));
    }
    // if((address.toString().startsWith("https://android.clients.google.com/music/mplay")) && deviceId != null)
    // {
    // request.addHeader("X-Device-ID", deviceId);
    // }

    return request;
}

From source file:com.sun.identity.proxy.client.ClientHandler.java

/**
 * Submits the exchange request to the remote server. Creates and
 * populates the exchange response from that provided by the remote server.
 */// www  .  jav  a 2  s. co  m
@Override
public void handle(Exchange exchange) throws IOException, HandlerException {
    // recover any previous response connection, if present
    if (exchange.response != null && exchange.response.entity != null) {
        exchange.response.entity.close();
    }

    HttpRequestBase clientRequest = (exchange.request.entity != null ? new EntityRequest(exchange.request)
            : new NonEntityRequest(exchange.request));

    clientRequest.setURI(exchange.request.uri);

    // connection headers to suppress
    CIStringSet suppressConnection = new CIStringSet();

    // parse request connection headers to be treated as hop-to-hop
    suppressConnection.clear();
    suppressConnection.addAll(getConnectionHeaders(exchange.request.headers));

    // request headers
    for (String name : exchange.request.headers.keySet()) {
        if (!SUPPRESS_REQUEST_HEADERS.contains(name) && !suppressConnection.contains(name)) {
            for (String value : exchange.request.headers.get(name)) {
                clientRequest.addHeader(name, value);
            }
        }
    }

    HttpResponse clientResponse = httpClient.execute(clientRequest);

    exchange.response = new Response();

    // response entity
    HttpEntity clientResponseEntity = clientResponse.getEntity();
    if (clientResponseEntity != null) {
        exchange.response.entity = clientResponseEntity.getContent();
    }

    // response status line
    StatusLine statusLine = clientResponse.getStatusLine();
    exchange.response.version = statusLine.getProtocolVersion().toString();
    exchange.response.status = statusLine.getStatusCode();
    exchange.response.reason = statusLine.getReasonPhrase();

    // parse response connection headers to be suppressed in response
    suppressConnection.clear();
    suppressConnection.addAll(getConnectionHeaders(exchange.response.headers));

    // response headers
    for (HeaderIterator i = clientResponse.headerIterator(); i.hasNext();) {
        Header header = i.nextHeader();
        String name = header.getName();
        if (!SUPPRESS_RESPONSE_HEADERS.contains(name) && !suppressConnection.contains(name)) {
            exchange.response.headers.add(name, header.getValue());
        }
    }

    // TODO: decide if need to try-finally to call httpRequest.abort?
}

From source file:org.forgerock.openig.handler.ClientHandler.java

/**
 * Submits the exchange request to the remote server. Creates and populates the exchange
 * response from that provided by the remote server.
 *///www .j  a v a2s .  c om
@Override
public void handle(Exchange exchange) throws HandlerException, IOException {
    LogTimer timer = logger.getTimer().start();
    // recover any previous response connection, if present
    if (exchange.response != null && exchange.response.entity != null) {
        exchange.response.entity.close();
    }
    HttpRequestBase clientRequest = (exchange.request.entity != null ? new EntityRequest(exchange.request)
            : new NonEntityRequest(exchange.request));
    clientRequest.setURI(exchange.request.uri);
    // connection headers to suppress
    CaseInsensitiveSet suppressConnection = new CaseInsensitiveSet();
    // parse request connection headers to be suppressed in request
    suppressConnection.clear();
    suppressConnection.addAll(new ConnectionHeader(exchange.request).tokens);
    // request headers
    for (String name : exchange.request.headers.keySet()) {
        if (!SUPPRESS_REQUEST_HEADERS.contains(name) && !suppressConnection.contains(name)) {
            for (String value : exchange.request.headers.get(name)) {
                clientRequest.addHeader(name, value);
            }
        }
    }
    // send request
    HttpResponse clientResponse = httpClient.execute(clientRequest);
    exchange.response = new Response();
    // response entity
    HttpEntity clientResponseEntity = clientResponse.getEntity();
    if (clientResponseEntity != null) {
        exchange.response.entity = new BranchingStreamWrapper(clientResponseEntity.getContent(), storage);
    }
    // response status line
    StatusLine statusLine = clientResponse.getStatusLine();
    exchange.response.version = statusLine.getProtocolVersion().toString();
    exchange.response.status = statusLine.getStatusCode();
    exchange.response.reason = statusLine.getReasonPhrase();
    // parse response connection headers to be suppressed in response
    suppressConnection.clear();
    suppressConnection.addAll(new ConnectionHeader(exchange.response).tokens);
    // response headers
    for (HeaderIterator i = clientResponse.headerIterator(); i.hasNext();) {
        Header header = i.nextHeader();
        String name = header.getName();
        if (!SUPPRESS_RESPONSE_HEADERS.contains(name) && !suppressConnection.contains(name)) {
            exchange.response.headers.add(name, header.getValue());
        }
    }
    // TODO: decide if need to try-finally to call httpRequest.abort?
    timer.stop();
}

From source file:gmusic.api.api.comm.ApacheConnector.java

private HttpRequestBase adjustAddress(URI address, final HttpRequestBase request)
        throws MalformedURLException, URISyntaxException {
    if (address.toString().startsWith(HTTPS_PLAY_GOOGLE_COM_MUSIC_SERVICES)) {
        address = new URI(
                address.toURL() + String.format(COOKIE_FORMAT, getCookieValue("xt")) + "&format=jsarray");
    }//  ww  w .  j  av  a  2  s  .co  m

    request.setURI(address);

    if (authorizationToken != null) {
        request.addHeader(GOOGLE_LOGIN_AUTH_KEY, String.format(GOOGLE_LOGIN_AUTH_VALUE, authorizationToken));
    }
    // if((address.toString().startsWith("https://android.clients.google.com/music/mplay"))
    // && deviceId != null)
    // {
    // request.addHeader("X-Device-ID", deviceId);
    // }

    return request;
}