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:cn.edu.zzu.wemall.http.RequestParams.java

protected String getParamString() {
    return URLEncodedUtils.format(getParamsList(), HTTP.UTF_8);
}

From source file:tw.com.sti.store.api.android.AndroidApiService.java

/**
 * Auto Login(02): //from   w  w w .jav a 2  s .c  om
 */
public ApiInvoker<LoginRet> autoLogin() {
    String url = apiUrl.getAutoLoginUrl();
    ApiDataParseHandler<LoginRet> handler = ApiDataParseHandler.LOGIN_RET_PARSE_HANDLER;
    List<NameValuePair> nvps = createRequestParams();
    if (Logger.DEBUG) {
        L.d(url + "?" + URLEncodedUtils.format(nvps, "UTF-8"));
    }
    return new ApiInvoker<LoginRet>(this.config, handler, url, nvps);
}

From source file:edu.scripps.fl.pubchem.web.session.PCWebSession.java

protected InputStream getBioActivityAssaySummaryAsStream(List<Long> cids) throws Exception {
    List<NameValuePair> params = addParameters(new ArrayList<NameValuePair>(), "cid",
            StringUtils.join(cids, ","), "q", "cids", "exptype", "bioactivitycsv");
    URI uri = URIUtils.createURI("http", SITE, 80, "/assay/assay.cgi", URLEncodedUtils.format(params, "UTF-8"),
            null);//from w w  w  .j a va 2  s . c  om
    Document doc = new WaitOnRequestId(uri).asDocument();
    return getFtpLinkAsStream(doc);
}

From source file:org.mobicents.servlet.sip.restcomm.interpreter.RcmlInterpreter.java

public void sendStatusCallback() {
    final URI uri = context.getStatusCallback();
    final String method = context.getStatusCallbackMethod();
    final List<NameValuePair> parameters = context.getRcmlRequestParameters();
    if (uri != null) {
        try {/* w  w  w .j a va  2s.c o m*/
            final HttpRequestExecutor executor = new HttpRequestExecutor();
            final HttpRequestDescriptor request = new HttpRequestDescriptor(uri, method, parameters);
            executor.execute(request);
        } catch (final UnsupportedEncodingException exception) {
        } catch (final URISyntaxException exception) {
            save(notify(context, Notification.ERROR, 21609, uri, method,
                    URLEncodedUtils.format(parameters, "UTF-8"), null, null));
        } catch (final ClientProtocolException exception) {
            save(notify(context, Notification.ERROR, 11206, uri, method,
                    URLEncodedUtils.format(parameters, "UTF-8"), null, null));
        } catch (final IllegalArgumentException exception) {
        } catch (final IOException exception) {
            save(notify(context, Notification.ERROR, 11200, uri, method,
                    URLEncodedUtils.format(parameters, "UTF-8"), null, null));
        }
    }
}

From source file:com.prey.net.PreyRestHttpClient.java

public PreyHttpResponse getAutentication2(String url, Map<String, String> params, PreyConfig preyConfig)
        throws IOException {
    HttpGet method = null;/*from w w w.  j  av  a  2s .  c o m*/
    if (params != null) {
        method = new HttpGet(url + URLEncodedUtils.format(getHttpParamsFromMap(params), "UTF-8"));
    } else {
        method = new HttpGet(url);
    }
    method.setHeader("Accept", "*/*");
    PreyLogger.d("apikey:" + preyConfig.getApiKey());
    method.addHeader("Authorization", "Basic " + getCredentials(preyConfig.getApiKey(), "X"));
    //PreyLogger.d("Sending using 'GET' (Basic Authentication) - URI: " + method.getURI());
    HttpResponse httpResponse = httpclient.execute(method);
    PreyHttpResponse response = new PreyHttpResponse(httpResponse);
    //PreyLogger.d("Response from server: " + response.toString());
    method.removeHeaders("Authorization");
    return response;
}

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 GetEstimateRankResult getEstimateRank(GetEstimateRankRequest request) {

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

    List<NameValuePair> queryString = new ArrayList<>();
    if (request.getScore() != null)
        queryString.add(new BasicNameValuePair("score", String.valueOf(request.getScore())));

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

    return doRequest(get, GetEstimateRankResult.class);

}

From source file:com.nexmo.verify.sdk.NexmoVerifyClient.java

public CheckResult check(final String requestId, final String code, final String ipAddress)
        throws IOException, SAXException {
    if (requestId == null || code == null)
        throw new IllegalArgumentException("request ID and code parameters are mandatory.");

    log.debug("HTTP-Number-Verify-Check Client .. for [ " + requestId + " ] code [ " + code + " ] ");

    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("request_id", requestId));
    params.add(new BasicNameValuePair("code", code));

    if (ipAddress != null)
        params.add(new BasicNameValuePair("ip_address", ipAddress));

    String verifyCheckBaseUrl = this.baseUrl + PATH_VERIFY_CHECK;

    // Now that we have generated a query string, we can instanciate a HttpClient,
    // construct a POST method and execute to submit the request
    String response = null;//  ww  w . jav a  2  s . com
    for (int pass = 1; pass <= 2; pass++) {
        HttpPost httpPost = new HttpPost(verifyCheckBaseUrl);
        httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
        HttpUriRequest method = httpPost;
        String url = verifyCheckBaseUrl + "?" + 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-HTTP for url [ " + url + " ] ");
            response = new BasicResponseHandler().handleResponse(httpResponse);
            log.info(".. SUBMITTED NEXMO-HTTP URL [ " + url + " ] -- response [ " + response + " ] ");
            break;
        } catch (Exception e) {
            method.abort();
            log.info("communication failure: " + e);
            String exceptionMsg = e.getMessage();
            if (exceptionMsg.indexOf("Read timed out") >= 0) {
                log.info(
                        "we're still connected, but the target did not respond in a timely manner ..  drop ...");
            } else {
                if (pass == 1) {
                    log.info("... re-establish http client ...");
                    this.httpClient = null;
                    continue;
                }
            }

            // return a COMMS failure ...
            return new CheckResult(BaseResult.STATUS_COMMS_FAILURE, null, 0, null,
                    "Failed to communicate with NEXMO-HTTP url [ " + url + " ] ..." + e, true);
        }
    }

    Document doc;
    synchronized (this.documentBuilder) {
        doc = this.documentBuilder.parse(new InputSource(new StringReader(response)));
    }

    Element root = doc.getDocumentElement();
    if (!"verify_response".equals(root.getNodeName()))
        throw new IOException("No valid response found [ " + response + "] ");

    String eventId = null;
    int status = -1;
    float price = -1;
    String currency = null;
    String errorText = null;

    NodeList fields = root.getChildNodes();
    for (int i = 0; i < fields.getLength(); i++) {
        Node node = fields.item(i);
        if (node.getNodeType() != Node.ELEMENT_NODE)
            continue;

        String name = node.getNodeName();
        if ("event_id".equals(name)) {
            eventId = node.getFirstChild() == null ? null : node.getFirstChild().getNodeValue();
        } else if ("status".equals(name)) {
            String str = node.getFirstChild() == null ? null : node.getFirstChild().getNodeValue();
            try {
                if (str != null)
                    status = Integer.parseInt(str);
            } catch (NumberFormatException e) {
                log.error("xml parser .. invalid value in <status> node [ " + str + " ] ");
                status = BaseResult.STATUS_INTERNAL_ERROR;
            }
        } else if ("price".equals(name)) {
            String str = node.getFirstChild() == null ? null : node.getFirstChild().getNodeValue();
            try {
                if (str != null)
                    price = Float.parseFloat(str);
            } catch (NumberFormatException e) {
                log.error("xml parser .. invalid value in <price> node [ " + str + " ] ");
            }
        } else if ("currency".equals(name)) {
            currency = node.getFirstChild() == null ? null : node.getFirstChild().getNodeValue();
        } else if ("error_text".equals(name)) {
            errorText = node.getFirstChild() == null ? null : node.getFirstChild().getNodeValue();
        }
    }

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

    // Is this a temporary error ?
    boolean temporaryError = (status == BaseResult.STATUS_THROTTLED
            || status == BaseResult.STATUS_INTERNAL_ERROR);

    return new CheckResult(status, eventId, price, currency, errorText, temporaryError);
}

From source file:org.mobicents.servlet.sip.restcomm.interpreter.tagstrategy.voice.RecordTagStrategy.java

private void transcribeCallback(final URI uri, List<NameValuePair> parameters) {
    try {/*from   w w  w .  j  a v a 2 s .c o  m*/
        final HttpRequestExecutor executor = new HttpRequestExecutor();
        final HttpRequestDescriptor request = new HttpRequestDescriptor(uri, "POST", parameters);
        executor.execute(request);
    } catch (final UnsupportedEncodingException exception) {
    } catch (final URISyntaxException exception) {
        interpreter.notify(context, Notification.ERROR, 11100, uri, "POST",
                URLEncodedUtils.format(parameters, "UTF-8"), null, null);
    } catch (final ClientProtocolException exception) {
        interpreter.notify(context, Notification.ERROR, 11206, uri, "POST",
                URLEncodedUtils.format(parameters, "UTF-8"), null, null);
    } catch (final IllegalArgumentException exception) {
    } catch (final IOException exception) {
        interpreter.notify(context, Notification.ERROR, 11200, uri, "POST",
                URLEncodedUtils.format(parameters, "UTF-8"), null, null);
    }
}

From source file:com.basho.riak.client.util.ClientHelper.java

/**
 * Perform and HTTP request and return the resulting response using the
 * internal HttpClient.//from   ww w  .  j  a v  a 2s.  c  o m
 * 
 * @param bucket
 *            Bucket of the object receiving the request.
 * @param key
 *            Key of the object receiving the request or null if the request
 *            is for a bucket.
 * @param httpMethod
 *            The HTTP request to perform; must not be null.
 * @param meta
 *            Extra HTTP headers to attach to the request. Query parameters
 *            are ignored; they should have already been used to construct
 *            <code>httpMethod</code> and query parameters.
 * @param streamResponse
 *            If true, the connection will NOT be released. Use
 *            HttpResponse.getHttpMethod().getResponseBodyAsStream() to get
 *            the response stream; HttpResponse.getBody() will return null.
 * 
 * @return The HTTP response returned by Riak from executing
 *         <code>httpMethod</code>.
 * 
 * @throws RiakIORuntimeException
 *             If an error occurs during communication with the Riak server
 *             (i.e. HttpClient threw an IOException)
 */
HttpResponse executeMethod(String bucket, String key, HttpRequestBase httpMethod, RequestMeta meta,
        boolean streamResponse) {

    if (meta != null) {
        Map<String, String> headers = meta.getHeaders();
        for (String header : headers.keySet()) {
            httpMethod.addHeader(header, headers.get(header));
        }

        Map<String, String> queryParams = meta.getQueryParamMap();
        if (!queryParams.isEmpty()) {
            URI originalURI = httpMethod.getURI();
            List<NameValuePair> currentQuery = URLEncodedUtils.parse(originalURI, CharsetUtils.UTF_8.name());
            List<NameValuePair> newQuery = new LinkedList<NameValuePair>(currentQuery);

            for (Map.Entry<String, String> qp : queryParams.entrySet()) {
                newQuery.add(new BasicNameValuePair(qp.getKey(), qp.getValue()));
            }

            // For this, HC4.1 authors, I hate you
            URI newURI;
            try {
                newURI = URIUtils.createURI(originalURI.getScheme(), originalURI.getHost(),
                        originalURI.getPort(), originalURI.getPath(), URLEncodedUtils.format(newQuery, "UTF-8"),
                        null);
            } catch (URISyntaxException e) {
                throw new RiakIORuntimeException(e);
            }
            httpMethod.setURI(newURI);
        }
    }
    HttpEntity entity;
    try {
        org.apache.http.HttpResponse response = httpClient.execute(httpMethod);

        int status = 0;
        if (response.getStatusLine() != null) {
            status = response.getStatusLine().getStatusCode();
        }

        Map<String, String> headers = ClientUtils.asHeaderMap(response.getAllHeaders());
        byte[] body = null;
        InputStream stream = null;
        entity = response.getEntity();

        if (streamResponse) {
            stream = entity.getContent();
        } else {
            if (null != entity) {
                body = EntityUtils.toByteArray(entity);
            }
        }

        if (!streamResponse) {
            EntityUtils.consume(entity);
        }

        return new DefaultHttpResponse(bucket, key, status, headers, body, stream, response, httpMethod);
    } catch (IOException e) {
        httpMethod.abort();
        return toss(new RiakIORuntimeException(e));
    }
}