Example usage for org.apache.http.client.utils URLEncodedUtils format

List of usage examples for org.apache.http.client.utils URLEncodedUtils format

Introduction

In this page you can find the example usage for org.apache.http.client.utils URLEncodedUtils format.

Prototype

public static String format(final Iterable<? extends NameValuePair> parameters, final Charset charset) 

Source Link

Document

Returns a String that is suitable for use as an application/x-www-form-urlencoded list of parameters in an HTTP PUT or HTTP POST.

Usage

From source file:org.coffeebreaks.validators.nu.NuValidator.java

ValidationResult validateUri(URL url, ValidationRequest request) throws IOException {
    String parser = request.getValue("parser", null);
    HttpRequestBase method;// ww w  .j a v a2s  .c  o m
    List<NameValuePair> qParams = new ArrayList<NameValuePair>();
    qParams.add(new BasicNameValuePair("out", "json"));
    if (parser != null) {
        qParams.add(new BasicNameValuePair("parser", parser));
    }
    qParams.add(new BasicNameValuePair("doc", url.toString()));

    try {
        URI uri = new URI(baseUrl);
        URI uri2 = URIUtils.createURI(uri.getScheme(), uri.getHost(), uri.getPort(), uri.getPath(),
                URLEncodedUtils.format(qParams, "UTF-8"), null);
        method = new HttpGet(uri2);
        return validate(method);
    } catch (URISyntaxException e) {
        throw new IllegalArgumentException("invalid uri. Check your baseUrl " + baseUrl, e);
    }
}

From source file:com.mike.aframe.http.KJFileParams.java

public String getParamString() {
    return URLEncodedUtils.format(getParamsList(), "UTF-8");
}

From source file:org.cinedroid.util.CineworldAPIAssistant.java

/**
 * Sends a request tot he Cineworld API using a given {@link HttpClient}.
 * /*from w w  w .  j  a v a  2  s .  c  om*/
 * @param client
 * @param method
 *            the method to execute on the Cineworld server.
 * @param params
 *            params to execute the method with, must include a valid key. For other restrictions see the <a
 *            href="http://www.cineworld.co.uk/developer/api">API documentation</a>
 * @return the text returned by the server.
 * @throws CineworldAPIException
 *             if the request failed for any reason.
 */
public String sendRequest(final HttpClient client, final API_METHOD method, final NameValuePair... params)
        throws CineworldAPIException {
    URI uri;
    try {
        uri = URIUtils.createURI("http", CINEWORLD_API_URL, -1, method.getMethod(),
                URLEncodedUtils.format(Arrays.asList(params), "UTF-8"), null);
    } catch (URISyntaxException e) {
        throw new CineworldAPIException("Unable to create API request, invalid URL", e);
    }
    HttpGet request = new HttpGet(uri);

    HttpResponse response;
    try {
        response = client.execute(request);
    } catch (ClientProtocolException e) {
        throw new CineworldAPIException("Unable to execute API request", e);
    } catch (IOException e) {
        throw new CineworldAPIException("Unable to execute API request", e);
    }
    if (response.getStatusLine().getStatusCode() != HttpsURLConnection.HTTP_OK) {
        throw new CineworldAPIException(String.format("Unable to execute API request, Code:%d",
                response.getStatusLine().getStatusCode()));
    }

    String responseBody;
    try {
        responseBody = EntityUtils.toString(response.getEntity());
    } catch (ParseException e) {
        throw new CineworldAPIException("Unable to parse API response", e);
    } catch (IOException e) {
        throw new CineworldAPIException("Unable to read API response", e);
    }

    return responseBody;
}

From source file:org.apache.oozie.action.callback.CallbackActionExecutor.java

protected HttpResponse httpGetMethod(String urlString, List<Pair<String, String>> argumentList)
        throws IOException {
    HttpClient client = getHttpClient();
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    for (Pair pair : argumentList) {
        params.add(new BasicNameValuePair(pair.getFist().toString(), pair.getSecond().toString()));
    }/*from  ww  w . jav  a 2  s  .  c o m*/
    URI uri;
    try {
        uri = new URI(urlString + "?" + URLEncodedUtils.format(params, "utf-8"));
    } catch (URISyntaxException e) {
        throw new IOException(e);
    }
    HttpGet httpGet = new HttpGet(uri);
    HttpResponse response = null;
    try {
        response = client.execute(httpGet);
    } finally {
        httpGet.releaseConnection();
    }
    return response;
}

From source file:com.bazaarvoice.seo.sdk.util.BVUtility.java

public static String removeBVParameters(String url) {
    String newUrl = url;/* w  w w . j  a  va 2 s . c o m*/
    if (newUrl.contains("bvstate=")) {
        // Handle usecase with more parameters after bvstate
        newUrl = newUrl.replaceAll(BVConstant.BVSTATE_REGEX_WITH_TRAILING_SEPARATOR, "");

        // Handle usecase where bvstate is the last parameter
        if (newUrl.endsWith("?") | newUrl.endsWith("&")) {
            newUrl = newUrl.substring(0, newUrl.length() - 1);
        }
        if (newUrl.endsWith(BVConstant.ESCAPED_FRAGMENT_MULTIVALUE_SEPARATOR)) {
            newUrl = newUrl.substring(0, newUrl.length() - 3);
        }
    }

    if (hasBVQueryParameters(newUrl)) {
        final URI uri;
        try {
            uri = new URI(newUrl);
        } catch (URISyntaxException e) {
            return newUrl;
        }

        try {
            String newQuery = null;
            if (uri.getQuery() != null && uri.getQuery().length() > 0) {
                List<NameValuePair> newParameters = new ArrayList<NameValuePair>();
                List<NameValuePair> parameters = URLEncodedUtils.parse(uri.getQuery(),
                        Charset.forName("UTF-8"));
                for (NameValuePair parameter : parameters) {
                    if (!bvQueryParameters.contains(parameter.getName())) {
                        newParameters.add(parameter);
                    }
                }
                newQuery = newParameters.size() > 0
                        ? URLEncodedUtils.format(newParameters, Charset.forName("UTF-8"))
                        : null;
            }

            return new URI(uri.getScheme(), uri.getAuthority(), uri.getPath(), newQuery, null).toString();
        } catch (URISyntaxException e) {
            return newUrl;
        }
    }
    return newUrl;
}

From source file:org.craftercms.social.util.UGCHttpClient.java

public HttpResponse getAudit(String ticket, String ugcId)
        throws URISyntaxException, ClientProtocolException, IOException {
    List<NameValuePair> qparams = new ArrayList<NameValuePair>();
    qparams.add(new BasicNameValuePair("ticket", ticket));
    URI uri = URIUtils.createURI(scheme, host, port, appPath + "/api/2/audit/" + ugcId + ".json",
            URLEncodedUtils.format(qparams, HTTP.UTF_8), null);
    HttpGet httpget = new HttpGet(uri);
    HttpClient httpclient = new DefaultHttpClient();
    return httpclient.execute(httpget);
}

From source file:org.opencastproject.search.remote.SearchServiceRemoteImpl.java

/**
 * {@inheritDoc}/*from ww w.  j  a v a 2  s  .  c  o  m*/
 * 
 * @see org.opencastproject.search.api.SearchService#getByQuery(java.lang.String, int, int)
 */
@Override
public SearchResult getByQuery(String query, int limit, int offset) throws SearchException {
    List<NameValuePair> queryStringParams = new ArrayList<NameValuePair>();
    queryStringParams.add(new BasicNameValuePair("q", query));
    queryStringParams.add(new BasicNameValuePair("limit", Integer.toString(limit)));
    queryStringParams.add(new BasicNameValuePair("offset", Integer.toString(offset)));
    queryStringParams.add(new BasicNameValuePair("admin", Boolean.TRUE.toString()));
    HttpGet get = new HttpGet("/lucene.xml?" + URLEncodedUtils.format(queryStringParams, "UTF-8"));
    logger.debug("Sending remote query '{}'", get.getRequestLine().toString());
    HttpResponse response = getResponse(get);
    try {
        if (response != null)
            return SearchResultImpl.valueOf(response.getEntity().getContent());
    } catch (Exception e) {
        throw new SearchException("Unable to parse getByQuery response from remote search index", e);
    } finally {
        closeConnection(response);
    }
    throw new SearchException("Unable to perform getByQuery from remote search index");
}

From source file:uk.bowdlerize.API.java

public String getUserStatus() throws NoSuchPaddingException, UnsupportedEncodingException,
        NoSuchAlgorithmException, IllegalBlockSizeException, BadPaddingException, NoSuchProviderException,
        InvalidKeyException, InvalidKeySpecException, SignatureException {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    JSONObject json;//from  w ww.j  a  v  a  2  s.  co m
    /*HttpPost httpost = new HttpPost("https://api.blocked.org.uk/1.2/status/user");
    httpost.setHeader("Accept", "application/json");*/

    HttpGet httpGet = new HttpGet("https://api.blocked.org.uk/1.2/status/user");
    httpGet.setHeader("Accept", "application/json");

    String emailAddress = settings.getString(SETTINGS_EMAIL_ADDRESS, "");

    List<NameValuePair> nvps = new ArrayList<NameValuePair>();
    nvps.add(new BasicNameValuePair("email", emailAddress));
    nvps.add(new BasicNameValuePair("date", sDF.format(new Date())));
    nvps.add(new BasicNameValuePair("signature",
            SignHeaders(settings.getString(SETTINGS_USER_PRIVATE_KEY, ""), nvps)));

    try {
        httpGet.setURI(new URI(httpGet.getURI() + "?" + URLEncodedUtils.format(nvps, "utf-8")));
        HttpResponse response = httpclient.execute(httpGet);
        String rawJSON = EntityUtils.toString(response.getEntity());
        response.getEntity().consumeContent();
        Log.e("rawJSON", rawJSON);
        /*String sb = rawJSON;
        if (sb.length() > 4000) {
        Log.v("rawJSON", "sb.length = " + sb.length());
        int chunkCount = sb.length() / 4000;     // integer division
        for (int i = 0; i <= chunkCount; i++)
        {
            int max = 4000 * (i + 1);
            if (max >= sb.length()) {
                Log.v("rawJSON", "chunk " + i + " of " + chunkCount + ":" + sb.substring(4000 * i));
            } else {
                Log.v("rawJSON", "chunk " + i + " of " + chunkCount + ":" + sb.substring(4000 * i, max));
            }
        }
        }*/

        json = new JSONObject(rawJSON);

        if (json.getBoolean("success")) {
            return json.getString("status");
        } else {
            return null;
        }
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

From source file:com.windigo.http.client.ApacheHttpClient.java

/**
 * Create {@link HttpGet} request with given {@link String} url and
 * {@link NameValuePair} request parameters
 * /*  ww w.j  av  a2s  .  c om*/
 * @param url
 * @param nameValuePairs
 * @return {@link HttpGet}
 */
public HttpGet createHttpGetRequest(String url, List<NameValuePair> nameValuePairs) {

    String queryString = URLEncodedUtils.format(sanitizeParameters(nameValuePairs), HTTP.UTF_8);
    String fullUrlString = new StringBuilder(url + "?" + queryString).toString();
    HttpGet httpGet = new HttpGet(fullUrlString);
    Logger.log("[Request] Creating http get request " + httpGet.getURI());

    return httpGet;

}

From source file:org.jboss.shrinkwrap.tomcat_6.test.TomcatDeploymentIntegrationUnitTestCase.java

/**
 * Tests that we can execute an HTTP request and it's fulfilled as expected, 
 * proving our deployment succeeded/* ww w . ja  v  a 2 s  .co  m*/
 */
@Test
public void requestWebapp() throws Exception {
    // Get an HTTP Client
    final HttpClient client = new DefaultHttpClient();

    // Make an HTTP Request, adding in a custom parameter which should be echoed back to us
    final String echoValue = "ShrinkWrap>Tomcat Integration";
    final List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("to", PATH_ECHO_SERVLET));
    params.add(new BasicNameValuePair("echo", echoValue));
    final URI uri = URIUtils.createURI("http", HTTP_BIND_HOST, HTTP_BIND_PORT,
            NAME_WEBAPP + SEPARATOR + servletClass.getSimpleName(), URLEncodedUtils.format(params, "UTF-8"),
            null);
    final HttpGet request = new HttpGet(uri);

    // Execute the request
    log.info("Executing request to: " + request.getURI());
    final HttpResponse response = client.execute(request);
    System.out.println(response.getStatusLine());
    final HttpEntity entity = response.getEntity();
    if (entity == null) {
        Assert.fail("Request returned no entity");
    }

    // Read the result, ensure it's what we're expecting (should be the value of request param "echo")
    final BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent()));
    final String line = reader.readLine();
    Assert.assertEquals("Unexpected response from Servlet", echoValue, line);

}