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

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

Introduction

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

Prototype

public URI getURI() 

Source Link

Document

Returns the original request URI.

Usage

From source file:com.wareninja.android.commonutils.foursquareV2.http.AbstractHttpApi.java

/**
 * execute() an httpRequest catching exceptions and returning null instead.
 *
 * @param httpRequest//  w w  w . j  a v a  2 s .c  om
 * @return
 * @throws IOException
 */
public HttpResponse executeHttpRequest(HttpRequestBase httpRequest) throws IOException {
    if (DEBUG)
        Log.d(TAG,
                "executing HttpRequest for: " + httpRequest.getURI().toString() + "|" + httpRequest.getMethod()
        //+ "|" + httpRequest.getParams()
        //+ "|" + httpRequest.getAllHeaders()
        );
    /*
    // YG: just for debugging
    String headersStr = "";
    Header[] headers = httpRequest.getAllHeaders();
    for (Header header:headers) {
       headersStr += "|" + header.getName() + ":" + header.getValue();
    }
    String paramsStr = "";
    HttpParams params = httpRequest.getParams();
    paramsStr += "|fs_username=" + params.getParameter("fs_username");
    paramsStr += "|fs_password=" + params.getParameter("fs_password");
    if (DEBUG) Log.d(TAG, "HttpRequest Headers for: "
        + httpRequest.getURI().toString()
        + "|" + headersStr
        + "|" + paramsStr
        );
    */
    /*
    executing HttpRequest for: https://api.foursquare.com/v1/authexchange.json|POST
    HttpRequest Headers for: https://api.foursquare.com/v1/authexchange.json|
    |User-Agent:com.wareninja.android.mayormonster:1|Authorization:OAuth oauth_version="1.0",oauth_nonce="3568494401228",oauth_signature_method="HMAC-SHA1",oauth_consumer_key="P5BV4EIC5RC5MF1STSVPNLPRBF3M5S0OVXKRLIIN0QMU3BEA",oauth_token="",oauth_timestamp="1294862657",oauth_signature="dq7ej2ChkH8uXqLKJ2qICrcIUgk%3D"|
    |fs_username=null|fs_password=null
            
    HttpRequest Headers for: https://api.foursquare.com/v1/authexchange.json||User-Agent:com.wareninja.android.mayormonster:1|Authorization:OAuth oauth_version="1.0",oauth_nonce="3568497175618",oauth_signature_method="HMAC-SHA1",oauth_consumer_key="P5BV4EIC5RC5MF1STSVPNLPRBF3M5S0OVXKRLIIN0QMU3BEA",oauth_token="",oauth_timestamp="1294862657",oauth_signature="5BHzUcaSioV%2BdIX5HiB9C2AyuzA%3D"|
    |fs_username=null|fs_password=null
            
            
     */

    //-WareNinjaUtils.trustEveryone();//YG

    try {
        mHttpClient.getConnectionManager().closeExpiredConnections();
        return mHttpClient.execute(httpRequest);
    } catch (IOException e) {
        httpRequest.abort();
        throw e;
    }
}

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

protected String getSentData(HttpRequestBase httpMethod) {
    URI uri = httpMethod.getURI();
    StringBuilder sentData = new StringBuilder(httpMethod.getMethod()).append(" ").append(uri.getPath());

    if (uri.getQuery() != null) {
        sentData.append("?" + uri.getQuery());
    }/*from   w  w  w  .j  av  a2  s.  c  o  m*/

    sentData.append("\r\n");

    for (Header h : httpMethod.getAllHeaders()) {
        sentData.append(h);
    }

    sentData.append("\r\n");

    if (httpMethod instanceof HttpPost) {
        sentData.append(postData);
    }

    return sentData.toString();
}

From source file:census.couchdroid.CouchResponse.java

/**
 * C-tor parses the method results to build the CouchResponse object.
 * First, it reads the body (hence the IOException) from the method
 * Next, it checks the status codes to determine if the request was successful.
 * If there was an error, it parses the error codes.
 * @param method//from  ww  w .  j a v a2 s .  c o m
 * @throws IOException
 */
CouchResponse(HttpRequestBase req, HttpResponse response) throws IOException {
    headers = response.getAllHeaders();

    HttpEntity entity = response.getEntity();
    body = EntityUtils.toString(entity);

    path = req.getURI().getPath();

    statusCode = response.getStatusLine().getStatusCode();

    boolean isGet = (req instanceof HttpGet);

    boolean isPut = (req instanceof HttpPut);

    boolean isPost = (req instanceof HttpPost);

    boolean isDelete = (req instanceof HttpDelete);

    /*DEBUG*/ android.util.Log.e("CouchResponse", "status code = " + Integer.toString(statusCode));

    // TODO error handling sucks! must fix it!
    if ((statusCode == 400) || (statusCode == 404) || (statusCode == 405) || (statusCode == 409)
            || (statusCode == 412) || (statusCode == 500)) {
        JSONObject jbody = null;
        try {
            jbody = new JSONObject(body);
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        try {
            error_id = jbody.getString("error");
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        try {
            error_reason = jbody.getString("reason");
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    } else if ((isPut && statusCode == 201) || (isPost && statusCode == 201) || (isDelete && statusCode == 202)
            || (isDelete && statusCode == 200)) {

        if (path.endsWith("_bulk_docs")) { // Handle bulk doc update differently
            try {
                ok = (new JSONObject(body)).length() > 0;
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        } else {
            try {
                ok = (new JSONObject(body)).getBoolean("ok");
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    } else if ((req instanceof HttpGet) || ((req instanceof HttpPost) && statusCode == 200)) {
        ok = true;
    }
    //log.debug(toString());
}

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

protected final Element executeAndReadResponse(HttpRequestBase httpMethod)
        throws IOException, BadXmlResponseEx {

    final ClientHttpResponse httpResponse = doExecute(httpMethod);

    if (httpResponse.getRawStatusCode() > 399) {
        httpMethod.releaseConnection();//from w w  w  . j  a  va2  s .co  m
        throw new BadServerResponseEx(httpResponse.getStatusText() + " -- URI: " + httpMethod.getURI()
                + " -- Response Code: " + httpResponse.getRawStatusCode());
    }

    byte[] data = null;

    try {
        data = IOUtils.toByteArray(httpResponse.getBody());
        return Xml.loadStream(new ByteArrayInputStream(data));
    } catch (JDOMException e) {
        throw new BadXmlResponseEx(
                "Response: '" + new String(data, "UTF8") + "' (from URI " + httpMethod.getURI() + ")");
    } finally {
        httpMethod.releaseConnection();

        sentData = getSentData(httpMethod);
    }
}

From source file:com.basho.riak.client.http.util.TestClientHelper.java

@Test
public void execute_method_adds_query_params() throws IOException, URISyntaxException {
    stubResponse(true);//from w ww .  j av  a2s. c  o  m
    HttpRequestBase mockHttpRequestBase = mock(HttpRequestBase.class);
    when(mockHttpRequestBase.getURI()).thenReturn(new URI("http://127.0.0.1:8098/riak"));
    meta.setQueryParam("p", "v");

    impl.executeMethod(null, null, mockHttpRequestBase, meta);

    ArgumentCaptor<URI> uriCaptor = ArgumentCaptor.forClass(URI.class);

    verify(mockHttpClient).execute(mockHttpRequestBase);
    verify(mockHttpRequestBase).setURI(uriCaptor.capture());

    assertTrue(uriCaptor.getValue().getQuery().contains("p=v"));
}

From source file:com.ibm.sbt.services.client.ClientServicesException.java

public ClientServicesException(HttpResponse response, HttpRequestBase request) {
    this(null, createMessage(request, response));

    this.response = response;
    this.request = request;

    this.setResponseStatusCode(response.getStatusLine().getStatusCode());
    this.setReasonPhrase(response.getStatusLine().getReasonPhrase());
    this.setRequestURI(request.getURI());

    try {/*from ww  w . j a va  2s . c o m*/
        HttpEntity entity = response.getEntity();
        this.responseBody = EntityUtils.toString(entity, "UTF-8");
    } catch (IOException ioe) {
    }
}

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

/**
 * Builds the request URI appending the service end point to the path.<br>
 * <b>From:</b> /v1/foo/bar <br>
 * <b>to:</b>https://host:port/api/v1/foo/bar
 * //from  w  w w. j a  va  2 s  .co m
 * @param request
 *            the http request
 * 
 * @return the URI including the service end point
 */
private URI buildRequestURI(HttpRequestBase request) {
    String requestURL = getEndPoint() + request.getURI();

    try {
        requestURL = getEndPoint() + request.getURI();
        return new URI(requestURL);
    } catch (URISyntaxException e) {
        log.log(Level.SEVERE, requestURL + " could not be parsed as a URI reference");
        throw new RuntimeException(e);
    }
}

From source file:org.wikipedia.vlsergey.secretary.jwpf.HttpBot.java

protected final void performAction(final ContentProcessable contentProcessable)
        throws ActionException, ProcessException {
    List<HttpRequestBase> msgs = contentProcessable.getMessages();
    Iterator<HttpRequestBase> it = msgs.iterator();
    while (it.hasNext()) {
        HttpRequestBase httpMethod = it.next();
        if (getSite() != null) {

            URI uri = httpMethod.getURI();
            if (!uri.getPath().startsWith("/wiki/")) {
                try {
                    String str = getSite().getScheme() + "://" + getSite().getHost()
                            + (getSite().getPort() == -1 ? "" : ":" + getSite().getPort()) + getSite().getPath()
                            + uri.getPath() + (uri.getRawQuery() != null ? ("?" + uri.getRawQuery()) : "");
                    uri = new URI(str);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }//  w  w  w  .j a  v  a2  s  . c o m
                httpMethod.setURI(uri);
            } else {
                try {
                    String str = getSite().getScheme() + "://" + getSite().getHost()
                            + (getSite().getPort() == -1 ? "" : ":" + getSite().getPort()) + uri.getPath()
                            + (uri.getRawQuery() != null ? ("?" + uri.getRawQuery()) : "");
                    uri = new URI(str);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
                httpMethod.setURI(uri);
            }

            // logger.debug("path is: " + httpMethod.getURI());
        }

        try {
            while (true) {
                try {
                    if (httpMethod instanceof HttpGet) {
                        get((HttpGet) httpMethod, contentProcessable);
                    } else {
                        post((HttpPost) httpMethod, contentProcessable);
                    }
                    break;
                } catch (NoHttpResponseException exc) {
                    log.info("NoHttpResponseException, wait 6 seconds");
                    try {
                        Thread.sleep(5 * 1000);
                    } catch (InterruptedException e) {
                    }
                } catch (SocketException exc) {
                    log.info("SocketException, wait 5 seconds");
                    try {
                        Thread.sleep(5 * 1000);
                    } catch (InterruptedException e) {
                    }
                } catch (ServerErrorException exc) {
                    log.info("ServerErrorException (" + exc.getStatusLine() + "), wait 5 seconds");
                    try {
                        Thread.sleep(5 * 1000);
                    } catch (InterruptedException e) {
                    }
                } catch (DatabaseLagException exc) {
                    log.info("Database lag occured: " + exc.databaseLag);
                    int retryAfter = 6;
                    try {
                        retryAfter = Integer.parseInt(exc.retryAfter.getValue());
                    } catch (Exception exc2) {
                        // ignore
                    }
                    if (retryAfter != 0) {
                        log.info("Waiting for " + retryAfter + " seconds");
                        try {
                            Thread.sleep(retryAfter * 1000);
                        } catch (InterruptedException e) {
                        }
                    }
                }
            }
        } catch (IOException e1) {
            throw new ActionException(e1);
        }
    }
}

From source file:org.cogsurv.cogsurver.http.AbstractHttpApi.java

public CogSurvType executeHttpRequest(HttpRequestBase httpRequest, Parser<? extends CogSurvType> parser)
        throws CogSurvCredentialsException, CogSurvParseException, CogSurvException, IOException {
    if (DEBUG)//from   w ww. ja va2s .  co  m
        LOG.log(Level.FINE, "doHttpRequest: " + httpRequest.getURI());

    HttpResponse response = executeHttpRequest(httpRequest);
    if (DEBUG)
        LOG.log(Level.FINE, "executed HttpRequest for: " + httpRequest.getURI().toString());

    int statusCode = response.getStatusLine().getStatusCode();
    switch (statusCode) {
    case 200:
        InputStream is = response.getEntity().getContent();
        try {
            return parser.parse(AbstractParser.createXmlPullParser(is));
        } finally {
            is.close();
        }
    case 201:
        is = response.getEntity().getContent();
        try {
            return parser.parse(AbstractParser.createXmlPullParser(is));
        } finally {
            is.close();
        }

    case 401:
        response.getEntity().consumeContent();
        if (DEBUG)
            LOG.log(Level.FINE, "HTTP Code: 401");
        throw new CogSurvCredentialsException(response.getStatusLine().toString());

    case 404:
        response.getEntity().consumeContent();
        throw new CogSurvException(response.getStatusLine().toString());

    case 500:
        response.getEntity().consumeContent();
        if (DEBUG)
            LOG.log(Level.FINE, "HTTP Code: 500");
        throw new CogSurvException("Foursquare is down. Try again later.");

    default:
        if (DEBUG)
            LOG.log(Level.FINE, "Default case for status code reached: " + response.getStatusLine().toString());
        response.getEntity().consumeContent();
        throw new CogSurvException("Error connecting to Foursquare: " + statusCode + ". Try again later.");
    }
}

From source file:com.android.idtt.http.SyncHttpHandler.java

public ResponseStream sendRequest(HttpRequestBase request) throws HttpException {

    boolean retry = true;
    HttpRequestRetryHandler retryHandler = client.getHttpRequestRetryHandler();
    while (retry) {
        IOException exception = null;
        try {//from   w w w  .j a  v  a  2  s.  c o m
            if (request.getMethod().equals(HttpRequest.HttpMethod.GET.toString())) {
                _getRequestUrl = request.getURI().toString();
            } else {
                _getRequestUrl = null;
            }
            if (_getRequestUrl != null) {
                String result = HttpUtils.sHttpGetCache.get(_getRequestUrl);
                if (result != null) { // get
                    return new ResponseStream(result);
                }
            }
            HttpResponse response = client.execute(request, context);
            return handleResponse(response);
        } catch (UnknownHostException e) {
            exception = e;
            retry = retryHandler.retryRequest(exception, ++retriedTimes, context);
        } catch (IOException e) {
            exception = e;
            retry = retryHandler.retryRequest(exception, ++retriedTimes, context);
        } catch (NullPointerException e) {
            exception = new IOException(e);
            retry = retryHandler.retryRequest(exception, ++retriedTimes, context);
        } catch (HttpException e) {
            throw e;
        } catch (Exception e) {
            exception = new IOException(e);
            retry = retryHandler.retryRequest(exception, ++retriedTimes, context);
        } finally {
            if (!retry && exception != null) {
                throw new HttpException(exception);
            }
        }
    }
    return null;
}