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.dimasdanz.kendalipintu.util.JSONParser.java

public JSONObject makeHttpRequest(String url, String method, List<NameValuePair> params) {
    try {//from www.j a v a2  s.  c o m
        HttpParams httpParameters = new BasicHttpParams();
        HttpConnectionParams.setSoTimeout(httpParameters, so_timeout);
        HttpConnectionParams.setConnectionTimeout(httpParameters, co_timeout);
        if (method == "POST") {
            DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new UrlEncodedFormEntity(params));

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();
        } else if (method == "GET") {
            DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
            String paramString = URLEncodedUtils.format(params, "utf-8");
            url += "?" + paramString;
            HttpGet httpGet = new HttpGet(url);

            HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();
        }
    } catch (SocketTimeoutException e) {
        Log.e("SocketTimeoutException", "SocketTimeoutException");
        e.printStackTrace();
        return null;
    } catch (UnsupportedEncodingException e) {
        Log.e("UnsupportedEncodingException", "UnsupportedEncodingException");
        e.printStackTrace();
        return null;
    } catch (ClientProtocolException e) {
        Log.e("ClientProtocolException", "ClientProtocolException");
        e.printStackTrace();
        return null;
    } catch (IOException e) {
        Log.e("IOException", "IOException");
        e.printStackTrace();
        return null;
    }

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        json = sb.toString();
    } catch (Exception e) {
        Log.e("Buffer Error", "Buffer Error :  " + e.toString());
        return null;
    }

    try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
        return null;
    }
    return jObj;
}

From source file:org.mobicents.servlet.restcomm.http.client.HttpRequestDescriptor.java

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

From source file:org.apache.metron.maas.util.RESTUtil.java

public String encodeParams(Map<String, String> params) {
    Iterable<NameValuePair> nvp = Iterables.transform(params.entrySet(),
            kv -> new BasicNameValuePair(kv.getKey(), kv.getValue()));

    return URLEncodedUtils.format(nvp, Charset.defaultCharset());
}

From source file:net.fizzl.redditengine.impl.SubredditsApi.java

/**
 * Return subreddits recommended for the given subreddit(s).
 * //w w  w .  j a  v  a  2s .  c  o  m
 * @param reddits   subreddit names
 * @param omits      subreddit names to be filtered out
 * @return list of subreddits
 * @throws RedditEngineException
 */
public String[] getSubredditRecomendations(String[] reddits, String[] omits) throws RedditEngineException {
    StringBuilder path = new StringBuilder();
    path.append(UrlUtils.BASE_URL);
    path.append("/api/recommend/sr/");

    List<NameValuePair> params = new ArrayList<NameValuePair>();
    if (reddits != null) {
        params.add(new BasicNameValuePair("srnames", UrlUtils.toCommaDelimited(reddits)));
    }
    String strp = URLEncodedUtils.format(params, "UTF-8");
    path.append(strp);
    path.append(".json");
    String url = path.toString();

    List<NameValuePair> optional;
    if (omits == null) {
        optional = null;
    } else {
        optional = new ArrayList<NameValuePair>();
        optional.add(new BasicNameValuePair("omit", UrlUtils.toCommaDelimited(omits)));
    }

    List<String> retval = new ArrayList<String>();
    try {
        SimpleHttpClient client = SimpleHttpClient.getInstance();
        InputStream is = client.get(url, optional);
        retval = ListMapValue.fromInputStream(is, "sr_name");
        is.close();
    } catch (Exception e) {
        RedditEngineException re = new RedditEngineException(e);
        throw re;
    }

    return retval.toArray(new String[retval.size()]);
}

From source file:net.reichholf.dreamdroid.helpers.SimpleHttpClient.java

/**
 * @param uri//from www .jav a 2  s .  co m
 * @param parameters
 * @return
 */
public String buildUrl(String uri, List<NameValuePair> parameters) {
    String parms = URLEncodedUtils.format(parameters, HTTP.UTF_8).replace("+", "%20");
    if (!uri.contains("?"))
        uri += "?";
    return mPrefix + mProfile.getHost() + ":" + mProfile.getPortString() + uri + parms;
}

From source file:com.probam.updater.updater.impl.OUCUpdater.java

@Override
public void searchVersion() {
    mScanning = true;/*w  w w  .ja  v  a  2  s .co  m*/
    ArrayList<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
    params.add(new BasicNameValuePair("device", android.os.Build.DEVICE.toLowerCase()));
    params.add(new BasicNameValuePair("rom", getName()));
    new HttpStringReader(this).execute(URL + "?" + URLEncodedUtils.format(params, "UTF-8"));
}

From source file:com.talis.labs.api.sparql11.http.Sparql11HttpRdfUpdateTest.java

private static URI uri(final String graph) throws URISyntaxException {
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("graph", graph));
    URI uri = URIUtils.createURI(SCHEME, HOST, PORT, PATH, URLEncodedUtils.format(params, "UTF-8"), null);

    return uri;/*from  ww  w.  jav a  2 s  .co m*/
}

From source file:net.fizzl.redditengine.impl.SimpleHttpClient.java

/**
 * Calls HTTP GET with the Request-URI. Returns an InputStream of the response entity.
 * /*w  w  w.  ja v a 2  s  . c om*/
 * @param url      HTTP GET URL
 * @param params   GET parameters
 * @return         InputStream
 * @throws          ClientProtocolException
 * @throws          IOException
 * @throws          UnexpectedHttpResponseException
 */
public InputStream get(String url, List<NameValuePair> params)
        throws ClientProtocolException, IOException, UnexpectedHttpResponseException {
    if (params != null) {
        String strp = URLEncodedUtils.format(params, "UTF-8");
        url += "?" + strp;
    }
    HttpGet get = new HttpGet(url);
    return execute(get);
}

From source file:betting.JsonEntity.java

/**
 * Constructs a new {@link JsonEntity} with the list of parameters in the
 * specified encoding./*from  www .  ja  va  2 s .c  o m*/
 *
 * @param parameters
 *            iterable collection of name/value pairs
 * @param charset
 *            encoding the name/value pairs be encoded with
 *
 * @since 4.2
 */
public JsonEntity(final Iterable<? extends NameValuePair> parameters, final Charset charset) {
    super(URLEncodedUtils.format(parameters, charset != null ? charset : HTTP.DEF_CONTENT_CHARSET),
            ContentType.create(URLEncodedUtils.CONTENT_TYPE, charset));
}

From source file:rpi.rpiface.GetAsyncTask.java

/**
 * Se ejecuta en paralelo sin bloquear el sistema
 * //from   ww w . j a  v a  2 s  .  co m
 * @param param
 *            Array de parmetros: el primero se corresponde con el
 *            movimiento a realizar, el segundo con la direccin, el tercero
 *            con el puerto y el cuarto con el path
 */
protected Boolean doInBackground(String... param) {
    // Se asignan variables a los parmetros del asynctask
    String value = param[0];
    String rpi = param[1];
    String port = param[2];
    String rpiPath = param[3];
    String rpiParam = param[4];
    // Se crea un cliente http
    HttpClient httpClient = new DefaultHttpClient();
    // Se crea una lista con los parmetros
    List<NameValuePair> params = new LinkedList<NameValuePair>();
    params.add(new BasicNameValuePair(rpiParam, value));
    // Se pasa la lista a un string debidamente formateado
    String paramString = URLEncodedUtils.format(params, "iso-8859-15");
    // Se crea la url
    String url = rpi + ":" + port + rpiPath + "?" + paramString;
    Log.i(LOGTAG + " Asynctask" + " Http get:", url);
    // Se crea un objeto httpget
    HttpGet httpGet = new HttpGet(url);
    try {
        // Se ejecuta el cliente pasndole como parmetro la peticin get.
        HttpResponse response = httpClient.execute(httpGet);
        Log.i(LOGTAG + " Asynctask" + " Http Response:", response.toString());
    } catch (ClientProtocolException e) {
        Log.i(LOGTAG + " Asynctask" + " Http Response:", "Error en el protocolo http");
        e.printStackTrace();
        return false;
    } catch (IOException e) {
        Log.i(LOGTAG + " Asynctask" + " Http Response:",
                "Conexin abortada. No se pudo contactar con el servidor");
        e.printStackTrace();
        return false;
    }
    return true;

}