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.github.feribg.audiogetter.helpers.Utils.java

/**
 * @param path    relative path for the resource including / prefix
 * @param qparams NameValuePair list of parameters
 * @return a correctly formatted and urlencoded string
 * @throws URISyntaxException/*  w  ww.  j a  v a2  s.  c  o m*/
 */
public static URI getUri(String scheme, String path, List<NameValuePair> qparams) throws URISyntaxException {
    return URIUtils.createURI(scheme, Constants.Backend.API_HOST, -1, path,
            URLEncodedUtils.format(qparams, "UTF-8"), null);
}

From source file:com.nexmo.sns.sdk.NexmoSnsClient.java

public SnsServiceResult submit(final Request request) throws Exception {

    log.info("NEXMO-REST-SNS-SERVICE-CLIENT ... submit request [ " + request.toString() + " ] ");

    // Construct a query string as a list of NameValuePairs

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

    params.add(new BasicNameValuePair("api_key", this.apiKey));
    params.add(new BasicNameValuePair("api_secret", this.apiSecret));
    params.add(new BasicNameValuePair("cmd", request.getCommand()));
    if (request.getQueryParameters() != null)
        for (Map.Entry<String, String> entry : request.getQueryParameters().entrySet())
            params.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));

    //String baseUrl = https ? this.baseUrlHttps : this.baseUrlHttp;

    // Now that we have generated a query string, we can instanciate a HttpClient,
    // construct a POST or GET method and execute to submit the request
    String response = null;//from   w  w  w.  ja  v  a  2  s.c o m
    HttpPost method = new HttpPost(this.baseUrl);
    method.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
    String url = this.baseUrl + "?" + URLEncodedUtils.format(params, "utf-8");
    try {
        if (this.httpClient == null)
            this.httpClient = HttpClientUtils.getInstance(this.connectionTimeout, this.soTimeout)
                    .getNewHttpClient();
        HttpResponse httpResponse = this.httpClient.execute(method);
        int status = httpResponse.getStatusLine().getStatusCode();
        if (status != 200)
            throw new Exception(
                    "got a non-200 response [ " + status + " ] from Nexmo-HTTPS for url [ " + url + " ] ");
        response = new BasicResponseHandler().handleResponse(httpResponse);
        log.info(".. SUBMITTED NEXMO-HTTP URL [ " + url + " ] -- response [ " + response + " ] ");
    } catch (Exception e) {
        log.info("communication failure: " + e);
        method.abort();
        return new SnsServiceResult(request.getCommand(), SnsServiceResult.STATUS_COMMS_FAILURE,
                "Failed to communicate with NEXMO-HTTP url [ " + url + " ] ..." + e, null, null);
    }

    // parse the response doc ...

    /*
    We receive a response from the api that looks like this, parse the document
    and turn it into an instance of SnsServiceResult
            
        <nexmo-sns>
            <command>subscribe|publish</command>
            <resultCode>0</resultCode>
            <resultMessage>OK!</resultMessage>
            <transactionId>${transaction-id}</transactionId>
            <subscriberArn>${subscriber}</subscriberArn>
        </nexmo-sns>
            
    */

    Document doc = null;
    synchronized (this.documentBuilder) {
        try {
            doc = this.documentBuilder.parse(new InputSource(new StringReader(response)));
        } catch (Exception e) {
            throw new Exception("Failed to build a DOM doc for the xml document [ " + response + " ] ", e);
        }
    }

    String command = null;
    int resultCode = -1;
    String resultMessage = null;
    String transactionId = null;
    String subscriberArn = null;

    NodeList replies = doc.getElementsByTagName("nexmo-sns");
    for (int i = 0; i < replies.getLength(); i++) {
        Node reply = replies.item(i);
        NodeList nodes = reply.getChildNodes();

        for (int i2 = 0; i2 < nodes.getLength(); i2++) {
            Node node = nodes.item(i2);
            if (node.getNodeType() != Node.ELEMENT_NODE)
                continue;
            if (node.getNodeName().equals("command")) {
                command = node.getFirstChild() == null ? null : node.getFirstChild().getNodeValue();
            } else if (node.getNodeName().equals("resultCode")) {
                String str = node.getFirstChild() == null ? null : node.getFirstChild().getNodeValue();
                try {
                    resultCode = Integer.parseInt(str);
                } catch (Exception e) {
                    log.error("xml parser .. invalid value in <resultCode> node [ " + str + " ] ");
                    resultCode = SnsServiceResult.STATUS_INTERNAL_ERROR;
                }
            } else if (node.getNodeName().equals("resultMessage")) {
                resultMessage = node.getFirstChild() == null ? null : node.getFirstChild().getNodeValue();
            } else if (node.getNodeName().equals("transactionId")) {
                transactionId = node.getFirstChild() == null ? null : node.getFirstChild().getNodeValue();
            } else if (node.getNodeName().equals("subscriberArn")) {
                subscriberArn = node.getFirstChild() == null ? null : node.getFirstChild().getNodeValue();
            } else
                log.error("xml parser .. unknown node found in nexmo-sns [ " + node.getNodeName() + " ] ");
        }
    }

    if (resultCode == -1)
        throw new Exception("Xml Parser - did not find a <resultCode> node");

    return new SnsServiceResult(command, resultCode, resultMessage, transactionId, subscriberArn);
}

From source file:de.topicmapslab.couchtm.internal.utils.SysDB.java

/**
 * Method used to delete something in the database.
 * /*  w  w w .java  2s  .  c  om*/
 * @param query
 * @param key
 * @return result
 */
protected int deleteMethod(String query, String key) {
    int statusCode = 0;
    URI uri = null;
    if (key != null) {
        List<NameValuePair> pair = new ArrayList<NameValuePair>();
        pair.add(new BasicNameValuePair("rev", key));
        key = URLEncodedUtils.format(pair, "UTF-8");
    }
    try {
        uri = URIUtils.createURI("http", url, port, (dbName == null ? "" : dbName + "/") + query, key, null);
        delete = new HttpDelete(uri);
        client.execute(delete, responseHandler);
    } catch (Exception e) {
        System.err.println(uri.toString());
        e.printStackTrace();
    }
    return statusCode;
}

From source file:me.code4fun.roboq.Request.java

private String makeUrl(String url, Options opts) {
    String url1 = url;//w w  w  .  j av  a2  s. co m

    // expand path vars
    for (Map.Entry<String, Object> entry : opts.getPathVars().entrySet()) {
        String k = entry.getKey();
        url1 = url1.replace("${" + k + "}", o2s(entry.getValue(), ""));
    }

    // params
    ArrayList<NameValuePair> nvl = new ArrayList<NameValuePair>();
    for (Map.Entry<String, Object> entry : opts.getParams().entrySet()) {
        nvl.add(new BasicNameValuePair(entry.getKey(), o2s(entry.getValue(), "")));
    }
    if (nvl.isEmpty()) {
        return url1;
    } else {
        return url1 + "?" + URLEncodedUtils.format(nvl,
                selectValue(paramsEncoding, prepared != null ? prepared.paramsEncoding : null, "UTF-8"));
    }
}

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

public HttpResponse updateModerationStatus(String ticket, String ugcId, 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/" + ugcId + "/status.json",
            URLEncodedUtils.format(qparams, HTTP.UTF_8), null);
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(uri);
    StringEntity bodyEntity = new StringEntity(moderationStatus.toUpperCase(), "text/xml",
            HTTP.DEFAULT_CONTENT_CHARSET);
    httppost.setEntity(bodyEntity);//  ww  w  .  j  a  va2s . c  o m

    return httpclient.execute(httppost);

}

From source file:org.gdg.frisbee.android.api.GroupDirectory.java

public ApiRequest getTaggedEventList(final DateTime start, final DateTime end, final String tag,
        Response.Listener<ArrayList<TaggedEvent>> successListener, Response.ErrorListener errorListener) {

    ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new NameValuePair() {
        @Override/*from   w w w  .j a v a2s. c o  m*/
        public String getName() {
            return "tag";
        }

        @Override
        public String getValue() {
            return tag;
        }
    });

    params.add(new NameValuePair() {
        @Override
        public String getName() {
            return "start";
        }

        @Override
        public String getValue() {
            return "" + (int) (start.getMillis() / 1000);
        }
    });

    if (end != null) {
        params.add(new NameValuePair() {
            @Override
            public String getName() {
                return "end";
            }

            @Override
            public String getValue() {
                return "" + (int) (end.getMillis() / 1000);
            }
        });
    }
    params.add(new NameValuePair() {
        @Override
        public String getName() {
            return "_";
        }

        @Override
        public String getValue() {
            return "" + (int) (new DateTime().getMillis() / 1000);
        }
    });
    Type type = new TypeToken<ArrayList<TaggedEvent>>() {
    }.getType();

    String url = TAGGED_EVENTS_URL;
    url += "?" + URLEncodedUtils.format(params, "UTF-8");

    GsonRequest<Void, ArrayList<TaggedEvent>> eventReq = new GsonRequest<Void, ArrayList<TaggedEvent>>(
            Request.Method.GET, url, type, successListener, errorListener,
            GsonRequest.getGson(FieldNamingPolicy.IDENTITY));

    return new ApiRequest(eventReq);

}

From source file:com.caibowen.gplume.misc.test.HttpClientUtil.java

/**
 * Get???,URL???, ?http://www.g.cn/*from w ww  .  j a v a 2 s  .  c o  m*/
 *
 * @param url    ???
 * @param params ?, /
 * @return ??
 */
public static String setParam(String url, Map<String, ? extends Serializable> params, Charset charset) {
    if (charset == null)
        charset = Consts.UTF_8;
    if (params != null && params.size() > 0) {
        List<NameValuePair> qparams = getParamsList(params);
        if (qparams != null && qparams.size() > 0) {
            String formatParams = URLEncodedUtils.format(qparams, charset);
            url = url + (url.indexOf("?") < 0 ? "?" : "&") + formatParams;
        }
    }

    return url;
}

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

@Override
public SearchRequestResult search(List<SearchQuery> queries) throws IOException, OpacErrorException {

    last_query = queries;/*  www .  j  a  v a 2s . com*/

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

    if (sessid == null) {
        start();
    }
    int index = 0;
    int page = 1;
    String homebranch = "";

    params.add(new BasicNameValuePair("fsubmit", "1"));
    params.add(new BasicNameValuePair("sess", sessid));
    params.add(new BasicNameValuePair("art", "f"));
    params.add(new BasicNameValuePair("pagesize", String.valueOf(pagesize)));

    for (SearchQuery query : queries) {
        if (query.getKey().equals("_heidi_page")) {
            page = Integer.parseInt(query.getValue());
            params.add(new BasicNameValuePair("start", String.valueOf((page - 1) * pagesize + 1)));
        } else if (query.getKey().equals("_heidi_branch")) {
            homebranch = query.getValue();
        } else if (query.getKey().equals("f[teil2]")) {
            params.add(new BasicNameValuePair(query.getKey(), query.getValue()));
        } else {
            if (!query.getValue().equals("")) {
                index = addParameters(query.getKey(), query.getValue(), params, index);
            }
        }
    }

    params.add(new BasicNameValuePair("vr", "1"));

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

    while (index < 3) {
        index++;
        if (index != 3) {
            params.add(new BasicNameValuePair("op" + index, "AND"));
        }
        params.add(new BasicNameValuePair("kat" + index, "freitext"));
        params.add(new BasicNameValuePair("var" + index, ""));
    }

    // Homebranch selection
    httpGet(opac_url + "/zweigstelle.cgi?sess=" + sessid + "&zweig=" + homebranch, ENCODING, false,
            cookieStore);
    // The actual search
    String html = httpGet(opac_url + "/search.cgi?" + URLEncodedUtils.format(params, "UTF-8"), ENCODING, false,
            cookieStore);
    return parse_search(html, page);
}

From source file:org.jboss.shrinkwrap.mobicents.servlet.sip.test.MobicentsSipServletsDeploymentIntegrationUnitTestCase.java

/**
 * Tests that we can execute an HTTP request on a Converged SIP Servlets application
 * and it's fulfilled as expected by returning the SIP application name in addition
 * to the echo value, proving our deployment succeeded
 *//*from  ww w .  ja  v a  2s.com*/
@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>Tomcat Integration";
    final List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("to", PATH_ECHO_SERVLET));
    params.add(new BasicNameValuePair("echo", echoValue));
    final URI uri = URIUtils.createURI("http", BIND_HOST, HTTP_BIND_PORT,
            NAME_SIPAPP + 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);
    System.out.println(response.getStatusLine());
    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 + NAME_SIPAPP, line);

}