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:com.elogiclab.vosao.plugin.FlickrUtils.java

public static String getLoginUrl(String frob, String apiKey, String apiSecret, String perms) {
    StringBuilder result = new StringBuilder();
    result.append("http://flickr.com/services/auth/?");
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("perms", perms));
    params.add(new BasicNameValuePair("frob", frob));
    params.add(new BasicNameValuePair("api_key", apiKey));

    FlickrUtils.signParams(params, apiSecret);

    String qs = URLEncodedUtils.format(params, "UTF-8");
    result.append(qs);/*from   ww w . j  a va2 s  .  c  o m*/

    return result.toString();
}

From source file:com.oakhole.voa.utils.HttpClientUtils.java

/**
 * ?Get,?/*from ww  w  . j  a v a2 s . com*/
 *
 * @param uri
 * @param map
 * @return
 */
public static HttpEntity get(String uri, Map<String, String> map) {

    CloseableHttpClient httpClient = HttpClients.createDefault();
    List<NameValuePair> list = Lists.newArrayList();
    for (String key : map.keySet()) {
        list.add(new BasicNameValuePair(key, map.get(key)));
    }

    String param = URLEncodedUtils.format(list, CHARSET);
    String url = uri + "?" + param;
    HttpGet httpGet = new HttpGet(url);
    try {
        CloseableHttpResponse httpResponse = httpClient.execute(httpGet);
        httpResponse.close();
        return httpResponse.getEntity();
    } catch (IOException e) {
        logger.error(":{}", e.getMessage());
    }
    return null;
}

From source file:org.epop.dataprovider.googlescholar.GoogleScholarGetterFromId.java

static List<Literature> getFromId(String userId) {
    // http://scholar.google.it/citations?user=q21xxm4AAAAJ&pagesize=100
    List<NameValuePair> qparams = new ArrayList<NameValuePair>();
    qparams.add(new BasicNameValuePair("user", userId));
    qparams.add(new BasicNameValuePair("pagesize", "100"));

    URI uri;/*  ww  w  .  j  av  a  2s .c  om*/
    String responseBody = null;
    try {
        uri = URIUtils.createURI("http", GOOGLE_SCHOLAR, -1, "", URLEncodedUtils.format(qparams, "UTF-8"),
                null);
        uri = new URI(uri.toString().replace("citations/?", "citations?"));
        HttpGet httpget = new HttpGet(uri);
        System.out.println(httpget.getURI());
        HttpClient httpclient = new DefaultHttpClient();
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        responseBody = httpclient.execute(httpget, responseHandler);
        //System.out.println(responseBody);
        int counter = 1;
        String newResponseBody = responseBody;
        while (newResponseBody.contains("class=\"cit-dark-link\">Next &gt;</a>")) {
            URI newUri = new URI(uri.toString() + "&cstart=" + counter * 100);
            httpget = new HttpGet(newUri);
            System.out.println(httpget.getURI());
            httpclient = new DefaultHttpClient();
            newResponseBody = httpclient.execute(httpget, responseHandler);
            //System.out.println(newResponseBody);
            responseBody = responseBody + newResponseBody;
            counter++;
        }
    } catch (URISyntaxException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    // return the result as string
    return parsePage(new StringReader(responseBody));
}

From source file:ch.iterate.openstack.swift.model.Region.java

public URI getStorageUrl(String container, List<NameValuePair> parameters) {
    return URI.create(
            String.format("%s?%s", this.getStorageUrl(container), URLEncodedUtils.format(parameters, "UTF-8")));
}

From source file:windsekirun.qrreader.util.JsonReceiver.java

public String makeJsonCall(String url, int method, List<NameValuePair> params) {
    try {//w  w  w  .  ja  v  a2 s  .c o  m
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpEntity httpEntity;
        HttpResponse httpResponse = null;

        if (method == POST) {
            HttpPost httpPost = new HttpPost(url);
            if (params != null)
                httpPost.setEntity(new UrlEncodedFormEntity(params));
            httpResponse = httpClient.execute(httpPost);
        } else if (method == GET) {
            if (params != null) {
                String paramString = URLEncodedUtils.format(params, "utf-8");
                url += "?" + paramString;
            }
            HttpGet httpGet = new HttpGet(url);
            httpResponse = httpClient.execute(httpGet);
        }
        assert httpResponse != null;
        httpEntity = httpResponse.getEntity();
        response = EntityUtils.toString(httpEntity);
    } catch (IOException e) {
        e.printStackTrace();
    }

    return response;

}

From source file:com.hp.autonomy.hod.client.api.authentication.SignedRequest.java

static SignedRequest sign(final Hmac hmac, final String endpoint,
        final AuthenticationToken<?, TokenType.HmacSha1> token, final Request<String, String> request) {
    final URIBuilder uriBuilder;

    try {//from w  ww .j a  v  a 2  s.  c o m
        uriBuilder = new URIBuilder(endpoint + request.getPath());
    } catch (final URISyntaxException e) {
        throw new IllegalArgumentException("Invalid endpoint or request path");
    }

    if (request.getQueryParameters() != null) {
        for (final Map.Entry<String, List<String>> entry : request.getQueryParameters().entrySet()) {
            for (final String value : entry.getValue()) {
                uriBuilder.addParameter(entry.getKey(), value);
            }
        }
    }

    final String bodyString;

    if (request.getBody() == null) {
        bodyString = null;
    } else {
        final List<NameValuePair> pairs = new LinkedList<>();

        for (final Map.Entry<String, List<String>> entry : request.getBody().entrySet()) {
            pairs.addAll(entry.getValue().stream().map(value -> new BasicNameValuePair(entry.getKey(), value))
                    .collect(Collectors.toList()));
        }

        bodyString = URLEncodedUtils.format(pairs, UTF8);
    }

    final String tokenString = hmac.generateToken(request, token);
    return new SignedRequest(uriBuilder.toString(), request.getVerb(), bodyString, tokenString);
}

From source file:edu.illinois.my.wiki.portlet.http.services.UriUtilsWrapper.java

@Override
public URI createUri(String urlPath, Parameters wikiParameters) {
    String serverAddress = server.asString();
    ImmutableList<NameValuePair> parameters = wikiParameters.asNameValuePairs();
    String path = URLEncodedUtils.format(parameters, ENCODING);
    try {//from   www .  ja  v a2  s .c  o  m
        return URIUtils.createURI(SECURE_HTTP, serverAddress, defaultPort, urlPath, path, fragment);
    } catch (URISyntaxException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.switchfly.inputvalidation.sanitizer.UrlStripHtmlSanitizer.java

@Override
public String execute(String content) {
    if (StringUtils.isBlank(content)) {
        return content;
    }/* w  w w  . j  a  v  a2  s  .c  o  m*/

    URI uri;
    try {
        uri = new URI(content);
    } catch (URISyntaxException e) {
        throw new RuntimeException(e);
    }

    List<NameValuePair> cleanedPairs = parse(uri);

    String queryString = cleanedPairs.isEmpty() ? null : URLEncodedUtils.format(cleanedPairs, ENCODING);

    try {
        return URIUtils.createURI(uri.getScheme(), uri.getHost(), uri.getPort(), uri.getPath(), queryString,
                uri.getFragment()).toString();
    } catch (URISyntaxException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.urucas.services.JSONFileRequest.java

@SuppressWarnings("deprecation")
@Override//from w  w w.ja  v a 2 s .c  o m
protected String doInBackground(String... uri) {

    HttpClient httpclient = new DefaultHttpClient();

    // add request params
    StringBuffer url = new StringBuffer(uri[0]).append("?")
            .append(URLEncodedUtils.format(getParams(), "UTF-8"));

    HttpPost _post = new HttpPost(url.toString());
    HttpContext localContext = new BasicHttpContext();

    Log.i("url ---->", url.toString());

    MultipartEntity _entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    for (int index = 0; index < getParams().size(); index++) {
        try {
            _entity.addPart(getParams().get(index).getName(),
                    new StringBody(getParams().get(index).getValue()));
        } catch (UnsupportedEncodingException e) {
        }
    }

    _entity.addPart("imagen", new FileBody(file));

    _post.setEntity(_entity);

    HttpResponse response;

    String responseString = null;
    // execute
    try {
        response = httpclient.execute(_post, localContext);
        StatusLine statusLine = response.getStatusLine();
        if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            response.getEntity().writeTo(out);
            out.close();
            responseString = out.toString();
            if (isCancelled()) {
                rsh.onError("Task cancel");
            }

        } else {
            //Closes the connection.
            response.getEntity().getContent().close();
            Log.i("status", String.valueOf(statusLine.getStatusCode()));
            throw new IOException(statusLine.getReasonPhrase());
        }
    } catch (ClientProtocolException e) {
        e.printStackTrace();
        //rsh.onError(e.getMessage());
    } catch (IOException e) {
        e.printStackTrace();
        //rsh.onError(e.getMessage());      
    }
    return responseString;
}

From source file:com.thoughtworks.go.spark.SparkController.java

default String controllerPath(Map<String, String> params) {
    if (params == null || params.isEmpty()) {
        return controllerBasePath();
    } else {//  www  .j a  v a 2  s  .c o m
        List<BasicNameValuePair> queryParams = params.entrySet().stream()
                .map(entry -> new BasicNameValuePair(entry.getKey(), entry.getValue()))
                .collect(Collectors.toList());
        return controllerBasePath() + '?' + URLEncodedUtils.format(queryParams, "utf-8");
    }
}