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.ambraproject.wombat.service.remote.ApiAddress.java

public String getAddress() {
    return path + (parameters.isEmpty() ? "" : "?" + URLEncodedUtils.format(parameters, Charsets.UTF_8));
}

From source file:org.opencastproject.inspection.remote.MediaInspectionServiceRemoteImpl.java

/**
 * {@inheritDoc}/*from  w ww  .j ava2 s.  c  o  m*/
 * 
 * @see org.opencastproject.inspection.api.MediaInspectionService#inspect(java.net.URI)
 */
@Override
public Job inspect(URI uri) throws MediaInspectionException {
    List<NameValuePair> queryStringParams = new ArrayList<NameValuePair>();
    queryStringParams.add(new BasicNameValuePair("uri", uri.toString()));
    String url = "/inspect?" + URLEncodedUtils.format(queryStringParams, "UTF-8");
    logger.info("Inspecting media file at {} using a remote media inspection service", uri);
    HttpResponse response = null;
    try {
        HttpGet get = new HttpGet(url);
        response = getResponse(get);
        if (response != null) {
            Job job = JobParser.parseJob(response.getEntity().getContent());
            logger.info("Completing inspection of media file at {} using a remote media inspection service",
                    uri);
            return job;
        }
    } catch (Exception e) {
        throw new MediaInspectionException("Unable to inspect " + uri + " using a remote inspection service",
                e);
    } finally {
        closeConnection(response);
    }
    throw new MediaInspectionException("Unable to inspect " + uri + " using a remote inspection service");
}

From source file:org.auraframework.components.aurajstest.JSTestCaseModel.java

public JSTestCaseModel() throws QuickFixException {
    AuraContext context = Aura.getContextService().getCurrentContext();
    BaseComponent<?, ?> component = context.getCurrentComponent();

    TestCaseDef caseDef = (TestCaseDef) component.getAttributes().getValue("case");

    String baseUrl = component.getAttributes().getValue("url").toString();
    Set<Entry<String, Object>> attributes = caseDef.getAttributeValues().entrySet();
    List<NameValuePair> newParams = Lists.newArrayList();
    String hash = "";
    if (!attributes.isEmpty()) {
        for (Entry<String, Object> entry : attributes) {
            String key = entry.getKey();
            String value = entry.getValue().toString();
            if (key.equals("__layout")) {
                hash = value;//from ww  w.  ja  v a2s. c  o  m
            } else {
                newParams.add(new BasicNameValuePair(key, value));
            }
        }
    }
    newParams.add(new BasicNameValuePair("aura.test", caseDef.getDescriptor().getQualifiedName()));
    url = baseUrl + "&" + URLEncodedUtils.format(newParams, "UTF-8") + hash;
    count = ((TestSuiteDef) component.getAttributes().getValue("suite")).getTestCaseDefs().size();
}

From source file:com.hollowsoft.library.utility.request.HttpRequest.java

/**
 *
 * @param url//  w ww .ja va 2s  .c  om
 * @param nameValuePairList
 * @return
 * @throws RequestException
 */
public JsonNode doGet(final String url, final List<NameValuePair> nameValuePairList) throws RequestException {
    if (url == null || url.isEmpty()) {
        throw new IllegalArgumentException("The url cannot be null or empty.");
    }

    final String parameterString = URLEncodedUtils.format(nameValuePairList, Constants.DEFAULT_CHARSET.name());

    try {

        final HttpGet httpGet = new HttpGet(url + "?" + parameterString);

        final HttpEntity httpEntity = httpClient.execute(httpGet).getEntity();

        return new ObjectMapper().reader().readTree(httpEntity.getContent());

    } catch (final ClientProtocolException e) {
        throw new RequestException(e);

    } catch (final JsonProcessingException e) {
        throw new RequestException(e);

    } catch (final IllegalStateException e) {
        throw new RequestException(e);

    } catch (final IOException e) {
        throw new RequestException(e);
    }
}

From source file:com.amazon.s3.util.HttpUtils.java

/**
 * Creates an encoded query string from all the parameters in the specified
 * request.//  ww w . j  a v  a 2s. com
 * 
 * @param request
 *            The request containing the parameters to encode.
 * 
 * @return Null if no parameters were present, otherwise the encoded query
 *         string for the parameters present in the specified request.
 */
public static String encodeParameters(Request<?> request) {
    List<NameValuePair> nameValuePairs = null;
    if (request.getParameters().size() > 0) {
        nameValuePairs = new ArrayList<NameValuePair>(request.getParameters().size());
        for (Entry<String, String> entry : request.getParameters().entrySet()) {
            nameValuePairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
        }
    }

    String encodedParams = null;
    if (nameValuePairs != null) {
        encodedParams = URLEncodedUtils.format(nameValuePairs, DEFAULT_ENCODING);
    }

    return encodedParams;
}

From source file:com.allegrorom.ota.FetchRomInfoTask.java

@Override
protected RomInfo doInBackground(Void... notused) {
    if (!Utils.isROMSupported()) {
        error = context.getString(R.string.alert_unsupported_title);
        return null;
    }//from  w  w w .  ja va  2s.  c  om
    if (!Utils.dataAvailable(context)) {
        error = context.getString(R.string.alert_nodata_title);
        return null;
    }

    try {
        ArrayList<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
        params.add(new BasicNameValuePair("device", android.os.Build.DEVICE.toLowerCase()));
        params.add(new BasicNameValuePair("rom", Utils.getRomID()));

        HttpClient client = new DefaultHttpClient();
        HttpGet get = new HttpGet(Config.PULL_URL + "?" + URLEncodedUtils.format(params, "UTF-8"));
        HttpResponse r = client.execute(get);
        int status = r.getStatusLine().getStatusCode();
        HttpEntity e = r.getEntity();
        if (status == 200) {
            String data = EntityUtils.toString(e);
            JSONObject json = new JSONObject(data);

            if (json.has("error")) {
                Log.e("OTA::Fetch", json.getString("error"));
                error = json.getString("error");
                return null;
            }

            return new RomInfo(json.getString("rom"), json.getString("version"), json.getString("changelog"),
                    json.getString("url"), json.getString("md5"), Utils.parseDate(json.getString("date")));
        } else {
            if (e != null)
                e.consumeContent();
            error = "Server responded with error " + status;
            return null;
        }
    } catch (Exception e) {
        e.printStackTrace();
        error = e.getMessage();
    }

    return null;
}

From source file:com.example.mysqltest.ServiceHandler.java

public String makeServiceCall(String url, int method, List<NameValuePair> params) {
    try {/*  w ww  .  j  a  v a2s .  co  m*/

        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpEntity httpEntity = null;
        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);

        }
        httpEntity = httpResponse.getEntity();
        is = httpEntity.getContent();

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

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

    return response;
}

From source file:com.radioreddit.android.api.GetSongInfo.java

@Override
protected Boolean doInBackground(String... params) {
    final String cookie = params[0]; // This will be null if not logged in.

    // Prepare GET with cookie, execute it, parse response as JSON.
    JSONObject response = null;/*from  w ww.  j a va2s  .c om*/
    try {
        final HttpClient httpClient = new DefaultHttpClient();
        final List<NameValuePair> nameValuePairs = new ArrayList<>();
        nameValuePairs.add(new BasicNameValuePair("url", mSong.reddit_url));
        final HttpGet httpGet = new HttpGet(
                "http://www.reddit.com/api/info.json?" + URLEncodedUtils.format(nameValuePairs, "utf-8"));
        if (cookie != null) {
            // Using HttpContext, CookieStore, and friends didn't work.
            httpGet.setHeader("Cookie", "reddit_session=" + cookie);
        }
        httpGet.setHeader("User-Agent", RedditApi.USER_AGENT);
        final HttpResponse httpResponse = httpClient.execute(httpGet);
        response = new JSONObject(EntityUtils.toString(httpResponse.getEntity()));
    } catch (UnsupportedEncodingException e) {
        Log.i(RedditApi.TAG, "UnsupportedEncodingException while getting song info", e);
    } catch (ClientProtocolException e) {
        Log.i(RedditApi.TAG, "ClientProtocolException while getting song info", e);
    } catch (IOException e) {
        Log.i(RedditApi.TAG, "IOException while getting song info", e);
    } catch (ParseException e) {
        Log.i(RedditApi.TAG, "ParseException while getting song info", e);
    } catch (JSONException e) {
        Log.i(RedditApi.TAG, "JSONException while getting song info", e);
    }

    // Check for failure.
    if (response == null) {
        Log.i(RedditApi.TAG, "Response is null");
        return false;
    }

    // Get the info we want.
    final JSONObject data1 = response.optJSONObject("data");
    if (data1 == null) {
        Log.i(RedditApi.TAG, "First data is null");
        return false;
    }
    final String modhash = data1.optString("modhash", "");
    if (modhash.length() > 0) {
        mService.setModhash(modhash);
    }
    final JSONArray children = data1.optJSONArray("children");
    if (children == null) {
        Log.i(RedditApi.TAG, "Children is null");
        return false;
    }
    final JSONObject child = children.optJSONObject(0);
    if (child == null) {
        // This is common if the song hasn't been submitted to reddit yet
        //  so we intentionally don't log this case.
        return false;
    }
    final String kind = child.optString("kind");
    if (kind == null) {
        Log.i(RedditApi.TAG, "Kind is null");
        return false;
    }
    final JSONObject data2 = child.optJSONObject("data");
    if (data2 == null) {
        Log.i(RedditApi.TAG, "Second data is null");
        return false;
    }
    final String id = data2.optString("id");
    if (id == null) {
        Log.i(RedditApi.TAG, "Id is null");
        return false;
    }
    final int score = data2.optInt("score");
    Boolean likes = null;
    if (!data2.isNull("likes")) {
        likes = data2.optBoolean("likes");
    }
    final boolean saved = data2.optBoolean("saved");

    // Modify song with collected info.
    mSong.reddit_id = kind + "_" + id;
    mSong.upvoted = (likes != null && likes);
    mSong.downvoted = (likes != null && !likes);
    mSong.votes = score;
    mSong.saved = saved;

    return true;
}

From source file:com.ammobyte.radioreddit.api.GetSongInfo.java

@Override
protected Boolean doInBackground(String... params) {
    final String cookie = params[0]; // This will be null if not logged in

    // Prepare GET with cookie, execute it, parse response as JSON
    JSONObject response = null;/*from   ww w  . j ava 2  s .  c  o m*/
    try {
        final HttpClient httpClient = new DefaultHttpClient();
        final List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        nameValuePairs.add(new BasicNameValuePair("url", mSong.reddit_url));
        final HttpGet httpGet = new HttpGet(
                "http://www.reddit.com/api/info.json?" + URLEncodedUtils.format(nameValuePairs, "utf-8"));
        if (cookie != null) {
            // Using HttpContext, CookieStore, and friends didn't work
            httpGet.setHeader("Cookie", "reddit_session=" + cookie);
        }
        httpGet.setHeader("User-Agent", RedditApi.USER_AGENT);
        final HttpResponse httpResponse = httpClient.execute(httpGet);
        response = new JSONObject(EntityUtils.toString(httpResponse.getEntity()));
    } catch (UnsupportedEncodingException e) {
        Log.i(RedditApi.TAG, "UnsupportedEncodingException while getting song info", e);
    } catch (ClientProtocolException e) {
        Log.i(RedditApi.TAG, "ClientProtocolException while getting song info", e);
    } catch (IOException e) {
        Log.i(RedditApi.TAG, "IOException while getting song info", e);
    } catch (ParseException e) {
        Log.i(RedditApi.TAG, "ParseException while getting song info", e);
    } catch (JSONException e) {
        Log.i(RedditApi.TAG, "JSONException while getting song info", e);
    }

    // Check for failure
    if (response == null) {
        Log.i(RedditApi.TAG, "Response is null");
        return false;
    }

    // Get the info we want
    final JSONObject data1 = response.optJSONObject("data");
    if (data1 == null) {
        Log.i(RedditApi.TAG, "First data is null");
        return false;
    }
    final String modhash = data1.optString("modhash", "");
    if (modhash.length() > 0) {
        mService.setModhash(modhash);
    }
    final JSONArray children = data1.optJSONArray("children");
    if (children == null) {
        Log.i(RedditApi.TAG, "Children is null");
        return false;
    }
    final JSONObject child = children.optJSONObject(0);
    if (child == null) {
        // This is common if the song hasn't been submitted to reddit yet
        // so we intentionally don't log this case
        return false;
    }
    final String kind = child.optString("kind");
    if (kind == null) {
        Log.i(RedditApi.TAG, "Kind is null");
        return false;
    }
    final JSONObject data2 = child.optJSONObject("data");
    if (data2 == null) {
        Log.i(RedditApi.TAG, "Second data is null");
        return false;
    }
    final String id = data2.optString("id");
    if (id == null) {
        Log.i(RedditApi.TAG, "Id is null");
        return false;
    }
    final int score = data2.optInt("score");
    Boolean likes = null;
    if (!data2.isNull("likes")) {
        likes = data2.optBoolean("likes");
    }
    final boolean saved = data2.optBoolean("saved");

    // Modify song with collected info
    if (kind != null && id != null) {
        mSong.reddit_id = kind + "_" + id;
    } else {
        mSong.reddit_id = null;
    }
    mSong.upvoted = (likes != null && likes == true);
    mSong.downvoted = (likes != null && likes == false);
    mSong.votes = score;
    mSong.saved = saved;

    return true;
}

From source file:es.upm.oeg.examples.watson.service.MachineTranslationService.java

public String translate(String text, String sid) throws IOException, URISyntaxException {

    logger.info("Text to translate :" + text);
    logger.info("Translation type :" + sid);

    List<NameValuePair> qparams = new ArrayList<NameValuePair>();
    qparams.add(new BasicNameValuePair("txt", text));
    qparams.add(new BasicNameValuePair("sid", sid));
    qparams.add(new BasicNameValuePair("rt", "text"));

    Executor executor = Executor.newInstance();
    URI serviceURI = new URI(baseURL).normalize();
    String auth = username + ":" + password;
    byte[] responseB = executor.execute(Request.Post(serviceURI)
            .addHeader("Authorization", "Basic " + Base64.encodeBase64String(auth.getBytes()))
            .bodyString(URLEncodedUtils.format(qparams, "utf-8"), ContentType.APPLICATION_FORM_URLENCODED))
            .returnContent().asBytes();/* www.j a va2s .c o  m*/

    String response = new String(responseB, "UTF-8");

    logger.info("Translation response :" + response);

    return response;

}