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:illab.nabal.proxy.TwitterContext.java

/**
 * Get OAuth-1.0a-ready HTTP request for test use only.
 * //from   www  .j  av a 2s  .c  o  m
 * @param httpMethod POST or GET
 * @param apiFullUrl
 * @param params
 * @param additionalOAuthParams
 * @param isAuthorizationCall true if the current request is a part of 
 *       OAuth authorization process
 * @return HttpUriRequest HttpPost or HttpGet
 * @throws Exception
 */
private HttpUriRequest getOAuthRequestBase(String httpMethod, String apiFullUrl, List<NameValuePair> params,
        List<NameValuePair> additionalOAuthParams, boolean isAuthorizationCall) throws Exception {

    HttpUriRequest httpRequest = null;

    // set OAuth parameters
    List<NameValuePair> oauthParams = ParameterHelper.addAllParams(
            // since Twitter checks timestamp in seconds, nonce should be GUARANTEED to be unique
            new BasicNameValuePair(OAUTH_NONCE, getSuperNonce()),
            new BasicNameValuePair(OAUTH_TIMESTAMP, getTimestamp()),
            new BasicNameValuePair(OAUTH_CONSUMER_KEY, mConsumerKey),
            new BasicNameValuePair(OAUTH_SIGNATURE_METHOD, HMAC_SHA1),
            new BasicNameValuePair(OAUTH_VERSION, OAUTH_VESION_1_0));

    // add additional OAuth parameters if exist
    if (additionalOAuthParams != null && additionalOAuthParams.size() > 0) {
        oauthParams.addAll(additionalOAuthParams);
    }

    // generate OAuth signature base string
    List<NameValuePair> baseStringParams = new ArrayList<NameValuePair>();
    baseStringParams.addAll(oauthParams);
    if (params != null && params.size() > 0) {
        baseStringParams.addAll(params);
    }
    String baseString = getBaseString(httpMethod, apiFullUrl, baseStringParams);

    // generate Authorization header string 
    String headerString = getOAuthHeaderString(
            ParameterHelper.addSignature(getSecretKey(), baseString, oauthParams));

    Log.d(TAG, "headerString : " + headerString);

    // add POST parameters to request body
    if (POST.equals(httpMethod)) {
        httpRequest = new HttpPost(new URI(apiFullUrl));
        if (params != null && params.size() > 0) {
            ((HttpPost) httpRequest)
                    .setEntity(new UrlEncodedFormEntity(params, org.apache.http.protocol.HTTP.UTF_8));
        }
    }

    // add GET query strings
    else if (GET.equals(httpMethod)) {
        String paramString = "";
        if (params != null && params.size() > 0) {
            paramString = "?" + URLEncodedUtils.format(params, org.apache.http.protocol.HTTP.UTF_8);
        }
        httpRequest = new HttpGet(new URI(apiFullUrl + paramString));
    }

    // add Authorization header to request header
    httpRequest.addHeader(AUTHORIZATION, headerString);

    // return HTTP request
    return httpRequest;
}

From source file:com.jzboy.couchdb.Database.java

/**
 * Retrieve a list of documents, optionally filtered by the parameters.
 * @param params   view API params/*from w  ww .j  a va 2s  . c  o m*/
 * @return if params contain include_docs:true, a list of the full documents; otherwise each Document in the result
 * list contains an id and rev only.
 * @see <a href="http://wiki.apache.org/couchdb/HTTP_Bulk_Document_API#Fetch_Multiple_Documents_With_a_Single_Request">
 * CouchDB Wiki for more information on valid parameters</a>
  * @throws IOException         if the HttpClient throws an IOException
 * @throws URISyntaxException   if there was a problem constructing a URI for this database
 * @throws CouchDBException      if CouchDB returns an error - response code >= 300. The response
 * details are encapsulated in the exception.
 */
public ArrayList<Document> getAllDocuments(List<NameValuePair> params)
        throws IOException, URISyntaxException, CouchDBException {
    String query = (params == null) ? null : URLEncodedUtils.format(params, "utf-8");
    JsonNode json = server.getHttpClient().get(URITemplates.allDocs(this, query));
    return parseDocuments(json);
}

From source file:com.ibm.ws.lars.rest.RepositoryContext.java

protected void doPostBadAttachmentWithContent(String assetId, String name, Attachment attachment,
        byte[] content, ContentType contentType, int expectedRC, String expectedMessage)
        throws ClientProtocolException, IOException, InvalidJsonAssetException {

    List<NameValuePair> qparams = new ArrayList<>();
    qparams.add(new BasicNameValuePair("name", name));
    String url = "/assets/" + assetId + "/attachments?" + URLEncodedUtils.format(qparams, "UTF-8");

    String response = doPostMultipart(url, name, attachment.toJson(), content, contentType, expectedRC);

    if (expectedMessage != null) {
        String errorMessage = parseErrorObject(response);
        assertEquals("Unexpected message from server", expectedMessage, errorMessage);
    }/*from  ww w  . j ava 2 s .  c  o m*/
}

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

/**
 * Report Application(09): Application/*from  w  w  w  . j  a v a  2s .c  o m*/
 */
public ApiInvoker<CommonRet> reportApp(String packageName, Integer appVersion, int reportId) {
    String[] paramNames;
    String[] paramValues;
    if (appVersion != null) {
        paramNames = new String[] { "lappv", "reportId" };
        paramValues = new String[] { String.valueOf(appVersion), String.valueOf(reportId) };
    } else {
        paramNames = new String[] { "reportId" };
        paramValues = new String[] { String.valueOf(reportId) };
    }
    String url = apiUrl.getApplicationReportUrl(packageName);
    ApiDataParseHandler<CommonRet> handler = ApiDataParseHandler.COMMON_RET_PARSE_HANDLER;
    List<NameValuePair> nvps = createRequestParams(paramNames, paramValues, true);
    if (Logger.DEBUG) {
        L.d(url + "?" + URLEncodedUtils.format(nvps, "UTF-8"));
    }
    return new ApiInvoker<CommonRet>(this.config, handler, url, nvps);
}

From source file:dataServer.StorageRESTClientManager.java

public String getMachineProperties(String machineId) {
    // Default HTTP client and common properties for requests
    requestUrl = null;/*w  w  w .  ja  v  a2s. c  o  m*/
    params = null;
    queryString = null;

    // Default HTTP response and common properties for responses
    HttpResponse response = null;
    ResponseHandler<String> handler = null;
    int status = 0;
    String body = null;

    // Query for machine properties
    requestUrl = new StringBuilder("http://" + storageLocation + ":" + storagePortRegistryC
            + storageRegistryContext + "/query/machine/properties");

    params = new LinkedList<NameValuePair>();
    params.add(new BasicNameValuePair("machineId", machineId));

    queryString = URLEncodedUtils.format(params, "utf-8");
    requestUrl.append("?");
    requestUrl.append(queryString);

    try {
        HttpGet query = new HttpGet(requestUrl.toString());
        query.setHeader("Content-type", "application/json");
        response = client.execute(query);

        // Check status code
        status = response.getStatusLine().getStatusCode();
        if (status != 200) {
            throw new RuntimeException("Failed! HTTP error code: " + status);
        }

        // Get body
        handler = new BasicResponseHandler();
        body = handler.handleResponse(response);

        //System.out.println("MACHINE PROPRIETIES: " + body);
        return body;
    } catch (Exception e) {
        System.out.println(e.getClass().getName() + ": " + e.getMessage());
        return null;
    }
}

From source file:org.dasein.cloud.tier3.APIHandler.java

private @Nonnull String getEndpoint(@Nonnull String resource, @Nullable String id,
        @Nullable NameValuePair... parameters) throws ConfigurationException, InternalException {

    ProviderContext ctx = provider.getContext();

    if (ctx == null) {
        throw new NoContextException();
    }/*from   w  ww . ja  v a2 s .c o m*/

    String endpoint = ctx.getEndpoint();

    if (endpoint == null) {
        logger.error("Null endpoint for the CenturyLink cloud");
        throw new ConfigurationException("Null endpoint for CenturyLink cloud");
    }
    while (endpoint.endsWith("/") && !endpoint.equals("/")) {
        endpoint = endpoint.substring(0, endpoint.length() - 1);
    }
    // TODO special V1 logic, replace when v2 is released
    endpoint += "/REST";
    if (resource.startsWith("/")) {
        endpoint = endpoint + resource;
    } else {
        endpoint = endpoint + "/" + resource;
    }
    if (id != null) {
        if (endpoint.endsWith("/")) {
            endpoint = endpoint + id;
        } else {
            endpoint = endpoint + "/" + id;
        }
    }
    if (parameters != null && parameters.length > 0) {
        while (endpoint.endsWith("/")) {
            endpoint = endpoint.substring(0, endpoint.length() - 1);
        }
        endpoint = endpoint + "?";
        ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();

        Collections.addAll(params, parameters);
        endpoint = endpoint + URLEncodedUtils.format(params, "utf-8");
    }
    logger.trace("Returning endpoint: " + endpoint);
    return endpoint;
}

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

/**
 * Rate Application(10): ?//from w  w w .j av  a  2  s  .c o m
 */
public ApiInvoker<CommonRet> rateApp(String packageName, Integer appVersion, int rating, String comment) {
    String[] paramNames;
    String[] paramValues;
    if (appVersion != null) {
        paramNames = new String[] { "lappv", "rating", "comment" };
        paramValues = new String[] { String.valueOf(appVersion), String.valueOf(rating), "" + comment };
    } else {
        paramNames = new String[] { "rating", "comment" };
        paramValues = new String[] { String.valueOf(rating), "" + comment };
    }
    String url = apiUrl.getApplicationRateUrl(packageName);
    ApiDataParseHandler<CommonRet> handler = ApiDataParseHandler.COMMON_RET_PARSE_HANDLER;
    List<NameValuePair> nvps = createRequestParams(paramNames, paramValues, true);
    if (Logger.DEBUG) {
        L.d(url + "?" + URLEncodedUtils.format(nvps, "UTF-8"));
    }
    return new ApiInvoker<CommonRet>(this.config, handler, url, nvps);
}

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

@Override
public ReservationResult reservation(DetailledItem item, Account acc, int useraction, String selection)
        throws IOException {
    String reservation_info = item.getReservation_info();
    String html = httpGet(opac_url + "/" + reservation_info, getDefaultEncoding());
    Document doc = Jsoup.parse(html);
    if (html.contains("Geheimnummer")) {
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        for (Element input : doc.select("#MainForm input")) {
            if (!input.attr("name").equals("BRWR") && !input.attr("name").equals("PIN")) {
                params.add(new BasicNameValuePair(input.attr("name"), input.attr("value")));
            }//  ww  w . java 2 s .  co  m
        }
        params.add(new BasicNameValuePair("BRWR", acc.getName()));
        params.add(new BasicNameValuePair("PIN", acc.getPassword()));
        html = httpGet(opac_url + "/" + doc.select("#MainForm").attr("action") + "?"
                + URLEncodedUtils.format(params, getDefaultEncoding()), getDefaultEncoding());
        doc = Jsoup.parse(html);
    }

    if (useraction == ReservationResult.ACTION_BRANCH) {
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        for (Element input : doc.select("#MainForm input")) {
            if (!input.attr("name").equals("Confirm")) {
                params.add(new BasicNameValuePair(input.attr("name"), input.attr("value")));
            }

        }
        params.add(new BasicNameValuePair("MakeResTypeDef.Reservation.RecipientLocn", selection));
        params.add(new BasicNameValuePair("Confirm", "1"));
        html = httpGet(opac_url + "/" + doc.select("#MainForm").attr("action") + "?"
                + URLEncodedUtils.format(params, getDefaultEncoding()), getDefaultEncoding());
        return new ReservationResult(MultiStepResult.Status.OK);
    }

    if (useraction == 0) {
        ReservationResult res = null;
        for (Node n : doc.select("#MainForm").first().childNodes()) {
            if (n instanceof TextNode) {
                if (((TextNode) n).text().contains("Entgelt")) {
                    res = new ReservationResult(ReservationResult.Status.CONFIRMATION_NEEDED);
                    List<String[]> details = new ArrayList<String[]>();
                    details.add(new String[] { ((TextNode) n).text().trim() });
                    res.setDetails(details);
                    res.setMessage(((TextNode) n).text().trim());
                    res.setActionIdentifier(MultiStepResult.ACTION_CONFIRMATION);
                }
            }
        }
        if (res != null)
            return res;
    }
    if (doc.select("#MainForm select").size() > 0) {
        ReservationResult res = new ReservationResult(ReservationResult.Status.SELECTION_NEEDED);
        Map<String, String> sel = new HashMap<String, String>();
        for (Element opt : doc.select("#MainForm select option")) {
            sel.put(opt.attr("value"), opt.text().trim());
        }
        res.setSelection(sel);
        res.setMessage("Bitte Zweigstelle auswhlen");
        res.setActionIdentifier(ReservationResult.ACTION_BRANCH);
        return res;
    }

    return new ReservationResult(ReservationResult.Status.ERROR);
}

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

public SearchResult[] search(String... requestIds) throws IOException, SAXException {
    if (requestIds == null || requestIds.length == 0)
        throw new IllegalArgumentException("request ID parameter is mandatory.");

    if (requestIds.length > MAX_SEARCH_REQUESTS)
        throw new IllegalArgumentException("too many request IDs. Max is " + MAX_SEARCH_REQUESTS);

    log.debug("HTTP-Number-Verify-Search Client .. for [ " + Arrays.toString(requestIds) + " ] ");

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

    params.add(new BasicNameValuePair("api_key", this.apiKey));
    params.add(new BasicNameValuePair("api_secret", this.apiSecret));

    if (requestIds.length == 1) {
        params.add(new BasicNameValuePair("request_id", requestIds[0]));
    } else {//from w ww.  j a  va2  s  . c o  m
        for (String requestId : requestIds)
            params.add(new BasicNameValuePair("request_ids", requestId));
    }

    String verifySearchBaseUrl = this.baseUrl + PATH_VERIFY_SEARCH;

    // 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;
    for (int pass = 1; pass <= 2; pass++) {
        HttpPost httpPost = new HttpPost(verifySearchBaseUrl);
        httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
        HttpUriRequest method = httpPost;
        String url = verifySearchBaseUrl + "?" + 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 SearchResult[] { new SearchResult(BaseResult.STATUS_COMMS_FAILURE, null, null, null,
                    null, 0, null, null, null, null, null, null, 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())) {
        // error response
        VerifyResult result = parseVerifyResult(root);
        return new SearchResult[] {
                new SearchResult(result.getStatus(), result.getRequestId(), null, null, null, 0, null, null,
                        null, null, null, null, null, result.getErrorText(), result.isTemporaryError()) };
    } else if (("verify_request").equals(root.getNodeName())) {
        return new SearchResult[] { parseSearchResult(root) };
    } else if ("verification_requests".equals(root.getNodeName())) {
        List<SearchResult> results = new ArrayList<>();

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

            if ("verify_request".equals(node.getNodeName()))
                results.add(parseSearchResult((Element) node));
        }

        return results.toArray(new SearchResult[results.size()]);
    } else {
        throw new IOException("No valid response found [ " + response + "] ");
    }
}

From source file:edu.rit.csh.androidwebnews.HttpsConnector.java

/**
 * Formats the URL String with the API key and all the extra parameters for GET requests
 *
 * @param addOn  - the add on to the url to format
 * @param addOns - List<NameValuePair> of extra parameters, can be empty
 * @return String - the formated String//from  w ww  .  j  a  va 2s  .  c  o m
 */
private URI formatUrl(String addOn, HashMap<String, String> addOns) {
    //if (!url.endsWith("?")) {
    //   url += "?";
    //}
    ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("api_key", sharedPref.getString("api_key", "")));
    params.add(new BasicNameValuePair("api_agent", "Android_Webnews"));
    if (addOns != null) {
        for (String key : addOns.keySet()) {
            params.add(new BasicNameValuePair(key, addOns.get(key)));
        }
    }
    try {
        return URIUtils.createURI("https", "webnews.csh.rit.edu", -1, "/" + addOn,
                URLEncodedUtils.format(params, "UTF-8"), null);
    } catch (URISyntaxException e) {
        return null;
    }
}