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.craftercms.social.util.UGCHttpClient.java

public HttpResponse dislike(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/ugc/dislike/" + ugcId + ".json",
            URLEncodedUtils.format(qparams, HTTP.UTF_8), null);
    HttpPost httppost = new HttpPost(uri);
    HttpClient httpclient = new DefaultHttpClient();
    return httpclient.execute(httppost);
}

From source file:es.trigit.gitftask.Conexion.Http.java

/**
 * Performs http PUT petition to server.
 *
 * @param url        URL to perform PUT petition.
 * @param parameters Parameters to include in petition.
 *
 * @return Response from the server./*from  ww w.ja va 2s .  c  om*/
 * @throws IOException If the <tt>parameters</tt> have errors, connection timed out,
 *                     socket timed out or other error related with the connection occurs.
 */
public static HttpResponse put(String url, ArrayList<NameValuePair> parameters) throws IOException {
    HttpParams httpParameters = new BasicHttpParams();
    int timeoutConnection = 10000;
    HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
    int timeoutSocket = 10000;
    HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

    HttpClient httpclient = new DefaultHttpClient(httpParameters);

    if (parameters != null) {
        String paramString = URLEncodedUtils.format(parameters, "utf-8");
        url += "?" + paramString;
    }

    HttpPut httpput = new HttpPut(url);

    HttpResponse response = httpclient.execute(httpput);

    return response;
}

From source file:census.couchdroid.CouchUpdate.java

/**
 * Return the parameters in a format compatible with the 'x-www-form-urlencoded' content type. This 
 * is called by the Database::updateDocument() method to perform a POST update
 * @return/* w  ww. ja  va  2  s .co  m*/
 */
public String getURLFormEncodedString() {
    return URLEncodedUtils.format(params, "UTF-8");
}

From source file:com.liferay.jsonwebserviceclient.JSONWebServiceClientImpl.java

@Override
public String doGet(String url, Map<String, String> parameters) throws CredentialException, IOException {

    List<NameValuePair> nameValuePairs = toNameValuePairs(parameters);

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

        url += "?" + queryString;
    }/*w  w w .j  ava 2  s .  c o m*/

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

    HttpGet httpGet = new HttpGet(url);

    return execute(httpGet);
}

From source file:com.wialon.remote.ApacheSdkHttpClient.java

private static String getUrlWithQueryString(String url, List<NameValuePair> params) {
    if (params != null) {
        String paramString = URLEncodedUtils.format(params, "UTF-8");
        if (!url.contains("?")) {
            url += "?" + paramString;
        } else {/*from   w  w w  .  j ava2s. c o  m*/
            url += "&" + paramString;
        }
    }
    return url;
}

From source file:com.todoist.TodoistBase.java

protected HttpGet request(String command, Map<String, Object> parameters, boolean secure) {
    List<NameValuePair> qparameters = new ArrayList<NameValuePair>();
    for (Map.Entry<String, Object> entry : parameters.entrySet()) {
        Object value = entry.getValue();
        String paramValue = value == null ? null : value.toString();
        qparameters.add(new BasicNameValuePair(entry.getKey(), paramValue));
    }/*from w ww. java2s  . com*/

    try {
        String scheme = secure ? "https" : "http";
        int port = secure ? 443 : 80;

        return new HttpGet(URIUtils.createURI(scheme, "todoist.com", port, "/API/" + command,
                URLEncodedUtils.format(qparameters, "UTF-8"), null));
    } catch (URISyntaxException e) {
        throw new TodoistException(e);
    }
}

From source file:com.github.seratch.signedrequest4j.SignedRequestApacheHCImpl.java

/**
 * {@inheritDoc}//w  w w  . j ava 2 s .com
 */
@Override
public HttpResponse doRequest(String url, HttpMethod method, Map<String, Object> requestParameters,
        String charset) throws IOException {

    HttpEntity entity = null;
    if (method == HttpMethod.GET) {
        List<NameValuePair> params = toNameValuePairList(requestParameters);
        String queryString = URLEncodedUtils.format(params, "UTF-8");
        if (queryString != null && !queryString.isEmpty()) {
            url = url.contains("?") ? url + "&" + queryString : url + "?" + queryString;
        }
    } else {
        List<NameValuePair> params = toNameValuePairList(requestParameters);
        entity = new UrlEncodedFormEntity(params, "UTF-8");
    }

    // read get parameters for signature base string
    readQueryStringAndAddToSignatureBaseString(url);

    HttpClient httpClient = new DefaultHttpClient();
    HttpUriRequest request = getRequest(method, url);
    httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectTimeoutMillis);
    httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, readTimeoutMillis);
    httpClient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, USER_AGENT);
    httpClient.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, charset);

    for (String name : headersToOverwrite.keySet()) {
        request.setHeader(name, headersToOverwrite.get(name));
    }

    String oAuthNonce = String.valueOf(new SecureRandom().nextLong());
    Long oAuthTimestamp = System.currentTimeMillis() / 1000;
    String signature = getSignature(url, method, oAuthNonce, oAuthTimestamp);
    String authorizationHeader = getAuthorizationHeader(signature, oAuthNonce, oAuthTimestamp);
    request.setHeader("Authorization", authorizationHeader);

    if (entity != null) {
        if (method == HttpMethod.POST) {
            HttpPost postRequest = (HttpPost) request;
            postRequest.setEntity(entity);
        } else if (method == HttpMethod.PUT) {
            HttpPut putRequest = (HttpPut) request;
            putRequest.setEntity(entity);
        }
    }

    org.apache.http.HttpResponse apacheHCResponse = httpClient.execute(request);
    if (apacheHCResponse.getStatusLine().getStatusCode() >= 400) {
        HttpResponse httpResponse = toReturnValue(apacheHCResponse, charset);
        throw new HttpException(apacheHCResponse.getStatusLine().getReasonPhrase(), httpResponse);
    }
    return toReturnValue(apacheHCResponse, charset);

}

From source file:com.synchophy.ui.CoverFlowActivity.java

private void refresh() {
    new JSONTask(this, true) {

        @Override/*from   ww w  .  j  a  v a2s  .c  o m*/
        public void post(Message obj) throws JSONException {
            Log.e("CoverFlowActivity", obj.toString());

            String token = JSONRequest.getToken(CoverFlowActivity.this);

            JSONArray images = (JSONArray) obj.obj;

            String[] imageGetParams = new String[images.length()];
            String[] albumLabels = new String[images.length()];
            String[] albumArtists = new String[images.length()];
            for (int i = 0; i < images.length(); i++) {
                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
                JSONObject imageDef = (JSONObject) images.get(i);
                nameValuePairs.add(new BasicNameValuePair("k", token));
                nameValuePairs.add(new BasicNameValuePair("artist", imageDef.getString("artist")));
                nameValuePairs.add(new BasicNameValuePair("album", imageDef.getString("album")));
                nameValuePairs.add(new BasicNameValuePair("a", "view"));

                final String paramString = URLEncodedUtils.format(nameValuePairs, "utf-8");
                imageGetParams[i] = paramString;
                albumLabels[i] = imageDef.getString("album");
                albumArtists[i] = imageDef.getString("artist");

                Intent msgIntent = new Intent(CoverFlowActivity.this, ImageDownloadService.class);
                msgIntent.putExtra(ImageDownloadService.IMAGE_URL, paramString);
                startService(msgIntent);

            }
            ImageAdapter coverImageAdapter = (ImageAdapter) coverFlow.getAdapter();
            coverImageAdapter.refresh(imageGetParams, albumLabels, albumArtists);
            coverImageAdapter.notifyDataSetChanged();

        }
    }.execute("image", new BasicNameValuePair("a", "list"),
            new BasicNameValuePair("filter", Boolean.toString(PlayerManager.isFiltering())));
}

From source file:io.gs2.ranking.Gs2RankingClient.java

/**
 * ?????<br>/*from   w  ww . j a  v a  2 s .  co m*/
 * <br>
 *
 * @param request 
        
 * @return ?
        
 */

public DescribeGameModeResult describeGameMode(DescribeGameModeRequest request) {

    String url = Gs2Constant.ENDPOINT_HOST + "/ranking/"
            + (request.getRankingTableName() == null || request.getRankingTableName().equals("") ? "null"
                    : request.getRankingTableName())
            + "/mode";

    List<NameValuePair> queryString = new ArrayList<>();
    if (request.getPageToken() != null)
        queryString.add(new BasicNameValuePair("pageToken", String.valueOf(request.getPageToken())));
    if (request.getLimit() != null)
        queryString.add(new BasicNameValuePair("limit", String.valueOf(request.getLimit())));

    if (queryString.size() > 0) {
        url += "?" + URLEncodedUtils.format(queryString, "UTF-8");
    }
    HttpGet get = createHttpGet(url, credential, ENDPOINT, DescribeGameModeRequest.Constant.MODULE,
            DescribeGameModeRequest.Constant.FUNCTION);
    if (request.getRequestId() != null) {
        get.setHeader("X-GS2-REQUEST-ID", request.getRequestId());
    }

    get.setHeader("X-GS2-ACCESS-TOKEN", request.getAccessToken());

    return doRequest(get, DescribeGameModeResult.class);

}

From source file:org.jboss.shrinkwrap.jetty_6.test.JettyDeploymentIntegrationUnitTestCase.java

/**
 * Doesn't really test anything now; shows end-user view only
 *//*from   ww w.j  av a2 s .c o  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>Jetty Integration";
    final List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("jsp", PATH_JSP));
    params.add(new BasicNameValuePair("echo", echoValue));
    final URI uri = URIUtils.createURI("http", "localhost", 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);
    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);

}