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.google.api.services.samples.youtube.cmdline.youtube_cmdline_topics_sample.Topics.java

/**
 * The Java Freebase client library does not include search functionality, so we created a call
 * directly via URL.  We use jackson functionality to put the JSON response into a POJO (Plain
 * Old Java Object).  The additional classes to create the object from JSON were created based on
 * the JSON response to make it easier to get the values we need.  For more info on jackson
 * classes, please search on the term./*  www  .jav a2s .  co m*/
 */
private static String getTopicId() throws IOException {

    /*
     * Returned as an empty string if we can't find a matching topicsId or there aren't any
     * results available.
     */
    String topicsId = "";

    /*
     * Get query term from user.  The "topics" parameter is just used as output to clarify that
     * we want a "topics" term (vs. a general "search" term).
     */
    String topicQuery = getInputQuery("topics");

    /*
     * Again, there isn't search functionality in the Freebase Java Library, so we have to call
     * directly against the URL.  Below we construct the proper URL, then use jackson classes to
     * convert the JSON into an object for reading.  You can find out more about the search calls
     * here: http://wiki.freebase.com/wiki/ApiSearch.
     */
    HttpClient httpclient = new DefaultHttpClient();
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("query", topicQuery));
    params.add(new BasicNameValuePair("limit", Long.toString(NUMBER_OF_TOPICS_RETURNED)));

    String serviceURL = "https://www.googleapis.com/freebase/v1/search";
    String url = serviceURL + "?" + URLEncodedUtils.format(params, "UTF-8");

    HttpResponse httpResponse = httpclient.execute(new HttpGet(url));
    HttpEntity entity = httpResponse.getEntity();

    if (entity != null) {
        InputStream instream = entity.getContent();
        try {
            /*
             * Converts JSON to a Tree.  I could have specified extra classes and done an exact map
             * from JSON to POJO, but I was trying to keep the sample within one Java file.  If the
             * .get() function calls here and in getUserChoice() aren't your cup of tea, feel free
             * to create those classes and use them with the mapper.readValue() function.
             */
            ObjectMapper mapper = new ObjectMapper();
            JsonNode rootNode = mapper.readValue(instream, JsonNode.class);

            // Check that the response is valid.
            if (rootNode.get("status").asText().equals("200 OK")) {
                // I know the "result" field contains the list of results I need.
                ArrayNode arrayNodeResults = (ArrayNode) rootNode.get("result");
                // Only place we set the topicsId for a valid selection in this function.
                topicsId = getUserChoice(arrayNodeResults);
            }
        } finally {
            instream.close();
        }
    }
    return topicsId;
}

From source file:com.addthis.hydra.query.web.GoogleDriveAuthentication.java

/**
 * Use the Google authorization token to obtain a Google access token.
 * Google OAuth2 your documentation is sorely lacking.
 *
 * @param kv store the access token as a (key, value) pair
 * @return true if the access token was retrieved
 *//*  w w w . ja va  2  s. com*/
static boolean gdriveAccessToken(KVPairs kv, ChannelHandlerContext ctx) throws Exception {
    CloseableHttpClient httpClient = null;
    CloseableHttpResponse httpResponse = null;
    if (kv.hasKey(autherror)) {
        sendErrorMessage(ctx,
                "Error while attempting to authorize google drive access: " + kv.getValue(autherror));
        return false;
    } else if (!kv.hasKey(authtoken)) {
        sendErrorMessage(ctx, "Error while attempting to authorize google drive access: "
                + "authorization token is missing.");
        return false;
    }
    try {
        String code = kv.getValue(authtoken);
        httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost("https://accounts.google.com/o/oauth2/token");
        httpPost.setHeader(HttpHeaders.Names.CONTENT_TYPE, URLEncodedUtils.CONTENT_TYPE);
        Set<NameValuePair> parameters = new HashSet<>();
        // Why is this redirect_uri required??? It appeared to be unused by the protocol.
        parameters.add(new BasicNameValuePair("redirect_uri",
                "http://" + generateTargetHostName() + ":2222/query/google/submit"));
        parameters.add(new BasicNameValuePair("code", code));
        parameters.add(new BasicNameValuePair("client_id", gdriveClientId));
        parameters.add(new BasicNameValuePair("client_secret", gdriveClientSecret));
        parameters.add(new BasicNameValuePair("grant_type", "authorization_code"));
        httpPost.setEntity(new StringEntity(URLEncodedUtils.format(parameters, Charset.defaultCharset()),
                StandardCharsets.UTF_8));
        httpResponse = httpClient.execute(httpPost);
        if (httpResponse.getStatusLine().getStatusCode() != HttpResponseStatus.OK.code()) {
            sendErrorMessage(ctx, "Error while attempting to exchange the authorization token "
                    + "for the access token: " + httpResponse.getStatusLine().getReasonPhrase());
            return false;
        }
        String responseEntity = EntityUtils.toString(httpResponse.getEntity());
        JSONObject response = new JSONObject(responseEntity);
        if (response.has("error")) {
            sendErrorMessage(ctx, "Error while attempting to exchange the authorization token "
                    + "for the access token: " + response.getString("error_description"));
            return false;
        } else if (!response.has("access_token")) {
            sendErrorMessage(ctx, "Error while attempting to exchange the authorization token "
                    + "for the access token: No access token received.");
            return false;
        }
        kv.addValue("accesstoken", response.getString("access_token"));
        return true;
    } finally {
        closeResource(httpResponse);
        closeResource(httpClient);
    }
}

From source file:com.bamobile.fdtks.util.Tools.java

public static String addImageToUrl(String url, String imageUrl) {
    if (!url.endsWith("?"))
        url += "?";

    List<NameValuePair> params = new LinkedList<NameValuePair>();
    params.add(new BasicNameValuePair("filename", imageUrl));
    String paramString = URLEncodedUtils.format(params, "utf-8");

    url += paramString;//from  w w w .  jav a2 s. com
    return url;
}

From source file:de.geeksfactory.opacclient.apis.Pica.java

@Override
public SearchRequestResult search(List<SearchQuery> query)
        throws IOException, OpacErrorException, JSONException {
    if (!initialised) {
        start();//from w w w . j  a  v a 2  s  . c  o m
    }

    List<NameValuePair> params = new ArrayList<>();

    int index = 0;
    start();

    params.add(new BasicNameValuePair("ACT", "SRCHM"));
    params.add(new BasicNameValuePair("MATCFILTER", "Y"));
    params.add(new BasicNameValuePair("MATCSET", "Y"));
    params.add(new BasicNameValuePair("NOSCAN", "Y"));
    params.add(new BasicNameValuePair("PARSE_MNEMONICS", "N"));
    params.add(new BasicNameValuePair("PARSE_OPWORDS", "N"));
    params.add(new BasicNameValuePair("PARSE_OLDSETS", "N"));

    for (SearchQuery singleQuery : query) {
        index = addParameters(singleQuery, params, index);
    }

    if (index == 0) {
        throw new OpacErrorException(stringProvider.getString(StringProvider.NO_CRITERIA_INPUT));
    }
    if (index > 4) {
        throw new OpacErrorException(
                stringProvider.getQuantityString(StringProvider.LIMITED_NUM_OF_CRITERIA, 4, 4));
    }

    String html = httpGet(
            opac_url + "/LNG=" + getLang() + "/DB=" + db + "/SET=1/TTL=1/CMD?"
                    + URLEncodedUtils.format(params, getDefaultEncoding()),
            getDefaultEncoding(), false, cookieStore);

    return parse_search(html, 1);
}

From source file:com.liferay.petra.json.web.service.client.BaseJSONWebServiceClientImpl.java

@Override
public String doGet(String url, Map<String, String> parameters, Map<String, String> headers)
        throws JSONWebServiceInvocationException, JSONWebServiceTransportException {

    if (!isNull(_contextPath)) {
        url = _contextPath + url;//  w w w. j  a  v a2  s.  com
    }

    List<NameValuePair> nameValuePairs = toNameValuePairs(parameters);

    if (!nameValuePairs.isEmpty()) {
        String queryString = URLEncodedUtils.format(nameValuePairs, _CHARSET);

        url += "?" + queryString;
    }

    if (_logger.isDebugEnabled()) {
        _logger.debug("Sending GET request to " + _login + "@" + _hostName + url);

        log("HTTP headers", headers);
        log("HTTP parameters", parameters);
    }

    HttpGet httpGet = new HttpGet(url);

    addHeaders(httpGet, headers);

    return execute(httpGet);
}

From source file:com.github.feribg.audiogetter.helpers.Utils.java

/**
 * Used to build an mp3 skull search query. An initial request might be needed to fetch the
 * CSRF token from the page source before searching
 * @param query//w  w w  .ja v  a  2  s  .c o  m
 * @param csrf
 * @return
 * @throws URISyntaxException
 */
public static URI getMp3SkullSearchURI(String query, String csrf) throws URISyntaxException {
    List<NameValuePair> qparams = new ArrayList<NameValuePair>();
    qparams.add(new BasicNameValuePair("q", query));
    qparams.add(new BasicNameValuePair("fckh", csrf));
    return URIUtils.createURI(Constants.Mp3skull.API_SCHEME, Constants.Mp3skull.API_HOST, -1,
            Constants.Mp3skull.API_SEARCH, URLEncodedUtils.format(qparams, "UTF-8"), null);
}

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

public HttpResponse getModerationStatus(String ticket, String moderationStatus)
        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/ugc/moderation/" + moderationStatus + ".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.opendatakit.aggregate.externalservice.AbstractExternalService.java

protected HttpResponse sendHttpRequest(String method, String url, HttpEntity entity,
        List<NameValuePair> qparams, CallingContext cc) throws IOException {

    HttpParams httpParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParams, SOCKET_ESTABLISHMENT_TIMEOUT_MILLISECONDS);
    HttpConnectionParams.setSoTimeout(httpParams, SERVICE_TIMEOUT_MILLISECONDS);

    // setup client
    HttpClientFactory factory = (HttpClientFactory) cc.getBean(BeanDefs.HTTP_CLIENT_FACTORY);
    HttpClient client = factory.createHttpClient(httpParams);

    // support redirecting to handle http: => https: transition
    HttpClientParams.setRedirecting(httpParams, true);
    // support authenticating
    HttpClientParams.setAuthenticating(httpParams, true);

    // redirect limit is set to some unreasonably high number
    // resets of the socket cause a retry up to MAX_REDIRECTS times,
    // so we should be careful not to set this too high...
    httpParams.setParameter(ClientPNames.MAX_REDIRECTS, 32);
    httpParams.setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true);

    // context holds authentication state machine, so it cannot be
    // shared across independent activities.
    HttpContext localContext = new BasicHttpContext();

    localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
    localContext.setAttribute(ClientContext.CREDS_PROVIDER, credsProvider);

    HttpUriRequest request = null;/*w  w  w  .  j a  va2 s . c  o m*/
    if (entity == null && (POST.equals(method) || PATCH.equals(method) || PUT.equals(method))) {
        throw new IllegalStateException("No body supplied for POST, PATCH or PUT request");
    } else if (entity != null && !(POST.equals(method) || PATCH.equals(method) || PUT.equals(method))) {
        throw new IllegalStateException("Body was supplied for GET or DELETE request");
    }

    URI nakedUri;
    try {
        nakedUri = new URI(url);
    } catch (Exception e) {
        e.printStackTrace();
        throw new IllegalStateException(e);
    }

    if (qparams == null) {
        qparams = new ArrayList<NameValuePair>();
    }
    URI uri;
    try {
        uri = new URI(nakedUri.getScheme(), nakedUri.getUserInfo(), nakedUri.getHost(), nakedUri.getPort(),
                nakedUri.getPath(), URLEncodedUtils.format(qparams, HtmlConsts.UTF8_ENCODE), null);
    } catch (URISyntaxException e1) {
        e1.printStackTrace();
        throw new IllegalStateException(e1);
    }
    System.out.println(uri.toString());

    if (GET.equals(method)) {
        HttpGet get = new HttpGet(uri);
        request = get;
    } else if (DELETE.equals(method)) {
        HttpDelete delete = new HttpDelete(uri);
        request = delete;
    } else if (PATCH.equals(method)) {
        HttpPatch patch = new HttpPatch(uri);
        patch.setEntity(entity);
        request = patch;
    } else if (POST.equals(method)) {
        HttpPost post = new HttpPost(uri);
        post.setEntity(entity);
        request = post;
    } else if (PUT.equals(method)) {
        HttpPut put = new HttpPut(uri);
        put.setEntity(entity);
        request = put;
    } else {
        throw new IllegalStateException("Unexpected request method");
    }

    HttpResponse resp = client.execute(request);
    return resp;
}