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:de.geeksfactory.opacclient.apis.Zones.java

@Override
public SearchRequestResult search(List<SearchQuery> queries) throws IOException, OpacErrorException {
    start();//from  w w  w.  j  ava  2  s.  com

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

    params.add(new BasicNameValuePair("Style", version18 ? "Portal2" : "Portal3"));
    params.add(new BasicNameValuePair("SubStyle", ""));
    params.add(new BasicNameValuePair("Lang", "GER"));
    params.add(new BasicNameValuePair("ResponseEncoding", "utf-8"));
    params.add(new BasicNameValuePair("Method", "QueryWithLimits"));
    params.add(new BasicNameValuePair("SearchType", "AdvancedSearch"));
    params.add(new BasicNameValuePair("TargetSearchType", "AdvancedSearch"));
    params.add(new BasicNameValuePair("DB", "SearchServer"));
    params.add(new BasicNameValuePair("q.PageSize", "10"));

    int index = 1;
    for (SearchQuery query : queries) {
        index = addParameters(query, params, index);
    }

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

    String html = httpGet(opac_url + "/" + searchobj + "?" + URLEncodedUtils.format(params, "UTF-8"),
            getDefaultEncoding());

    page = 1;

    return parse_search(html, page);
}

From source file:com.francisli.processing.http.HttpClient.java

/**
 * @param files HashMap: a collection of files to send to the server
 *///from   www  .  java  2  s .c  o m
public HttpRequest POST(String path, Map params, Map files) {
    //// clean up path a little bit- remove whitespace, add slash prefix
    path = path.trim();
    if (!path.startsWith("/")) {
        path = "/" + path;
    }
    //// finally, invoke request
    HttpPost post = new HttpPost(getHost().toURI() + path);
    MultipartEntity multipart = null;
    //// if files passed, set up a multipart request
    if (files != null) {
        multipart = new MultipartEntity();
        post.setEntity(multipart);
        for (Object key : files.keySet()) {
            Object value = files.get(key);
            if (value instanceof byte[]) {
                multipart.addPart((String) key, new ByteArrayBody((byte[]) value, "bytes.dat"));
            } else if (value instanceof String) {
                File file = new File((String) value);
                if (!file.exists()) {
                    file = parent.sketchFile((String) value);
                }
                multipart.addPart((String) key, new FileBody(file));
            }
        }
    }
    //// if params passed, format into a query string and append
    if (params != null) {
        if (multipart == null) {
            ArrayList<BasicNameValuePair> pairs = new ArrayList<BasicNameValuePair>();
            for (Object key : params.keySet()) {
                Object value = params.get(key);
                pairs.add(new BasicNameValuePair(key.toString(), value.toString()));
            }
            String queryString = URLEncodedUtils.format(pairs, HTTP.UTF_8);
            if (path.contains("?")) {
                path = path + "&" + queryString;
            } else {
                path = path + "?" + queryString;
            }
            try {
                post.setEntity(new UrlEncodedFormEntity(pairs, HTTP.UTF_8));
            } catch (UnsupportedEncodingException ex) {
                System.err.println("HttpClient: Unable to set POST data from parameters");
            }
        } else {
            for (Object key : params.keySet()) {
                Object value = params.get(key);
                try {
                    multipart.addPart((String) key, new StringBody((String) value));
                } catch (UnsupportedEncodingException ex) {
                    System.err.println("HttpClient: Unable to add " + key + ", " + value);
                }
            }
        }
    }
    if (useOAuth) {
        OAuthConsumer consumer = new CommonsHttpOAuthConsumer(oauthConsumerKey, oauthConsumerSecret);
        consumer.setTokenWithSecret(oauthAccessToken, oauthAccessTokenSecret);
        try {
            consumer.sign(post);
        } catch (Exception e) {
            System.err.println("HttpClient: Unable to sign POST request for OAuth");
        }
    }
    HttpRequest request = new HttpRequest(this, getHost(), post);
    request.start();
    return request;
}

From source file:cn.caimatou.canting.utils.http.asynchttp.RequestParams.java

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

From source file:uk.bowdlerize.API.java

public ISPMeta getISPMeta() {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    JSONObject json;//from  www  . j  a  v a  2s .  c  o  m

    try {
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("date", sDF.format(new Date())));
        nvps.add(new BasicNameValuePair("signature",
                SignHeaders(settings.getString(SETTINGS_PROBE_PRIVATE_KEY, ""), nvps)));
        nvps.add(new BasicNameValuePair("probe_uuid", settings.getString(SETTINGS_UUID, "")));

        HttpGet httpGet = new HttpGet("https://api.blocked.org.uk/1.2/status/ip");
        httpGet.setHeader("Accept", "application/json");

        httpGet.setURI(new URI(httpGet.getURI() + "?" + URLEncodedUtils.format(nvps, "utf-8")));
        HttpResponse response = httpclient.execute(httpGet);
        String rawJSON = EntityUtils.toString(response.getEntity());
        response.getEntity().consumeContent();
        Log.e("IP Raw JSON", rawJSON);
        json = new JSONObject(rawJSON);

        if (json.getBoolean("success")) {
            return new ISPMeta(json.getString("ip"), json.getString("isp"));
        } else {
            return null;
        }
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

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

@Override
public SearchRequestResult searchGetPage(int page)
        throws IOException, NotReachableException, OpacErrorException {
    List<NameValuePair> params = new ArrayList<NameValuePair>();

    params.add(new BasicNameValuePair("Style", "Portal3"));
    params.add(new BasicNameValuePair("SubStyle", ""));
    params.add(new BasicNameValuePair("Lang", "GER"));
    params.add(new BasicNameValuePair("ResponseEncoding", "utf-8"));
    if (page > this.page) {
        params.add(new BasicNameValuePair("Method", "PageDown"));
    } else {/*from ww  w . j a v  a2  s.c o m*/
        params.add(new BasicNameValuePair("Method", "PageUp"));
    }
    params.add(new BasicNameValuePair("PageSize", "10"));

    String html = httpGet(opac_url + "/" + searchobj + "?" + URLEncodedUtils.format(params, "UTF-8"),
            getDefaultEncoding());
    this.page = page;

    return parse_search(html, page);
}

From source file:io.gs2.timer.Gs2TimerClient.java

/**
 * ?????<br>/*ww w. ja  va 2  s  .c  o m*/
 * <br>
 *
 * @param request 
        
 * @return ?
        
 */

public DescribeTimerResult describeTimer(DescribeTimerRequest request) {

    String url = Gs2Constant.ENDPOINT_HOST + "/timerPool/"
            + (request.getTimerPoolName() == null || request.getTimerPoolName().equals("") ? "null"
                    : request.getTimerPoolName())
            + "/timer";

    List<NameValuePair> queryString = new ArrayList<>();
    if (request.getPageToken() != null)
        queryString.add(new BasicNameValuePair("pageToken", String.valueOf(request.getPageToken())));
    if (request.getLimit() != null)
        queryString.add(new BasicNameValuePair("limit", String.valueOf(request.getLimit())));

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

    return doRequest(get, DescribeTimerResult.class);

}

From source file:org.mahasen.client.Search.java

/**
 * @param propertyName//from   w w w  .  jav  a2 s. com
 * @param isRangeBase
 * @param value1
 * @param value2
 * @return
 * @throws IOException
 * @throws URISyntaxException
 * @throws AuthenticationExceptionException
 *
 * @throws MahasenClientException
 */
private HttpResponse sendRequest(String propertyName, boolean isRangeBase, String value1, String value2)
        throws IOException, URISyntaxException, AuthenticationExceptionException, MahasenClientException {

    httpclient = new DefaultHttpClient();
    HttpResponse response = null;

    String userName = clientLoginData.getUserName();
    String passWord = clientLoginData.getPassWord();
    String hostAndPort = clientLoginData.getHostNameAndPort();
    String userId = clientLoginData.getUserId(userName, passWord);
    Boolean isLogged = clientLoginData.isLoggedIn();
    System.out.println(" Is Logged : " + isLogged);

    if (isLogged == true) {

        httpclient = WebClientSSLWrapper.wrapClient(httpclient);

        ArrayList<NameValuePair> qparams = new ArrayList<NameValuePair>();
        qparams.add(new BasicNameValuePair("propertyName", propertyName));
        qparams.add(new BasicNameValuePair("isRangeBase", String.valueOf(isRangeBase)));

        if (isRangeBase == true) {
            qparams.add(new BasicNameValuePair("initialValue", value1));
            qparams.add(new BasicNameValuePair("lastValue", value2));
        } else {
            qparams.add(new BasicNameValuePair("propertyValue", value1));
        }

        URI uri = URIUtils.createURI("https", hostAndPort, -1, "/mahasen/search_ajaxprocessor.jsp",
                URLEncodedUtils.format(qparams, "UTF-8"), null);

        HttpPost httppost = new HttpPost(uri);

        System.out.println("executing request " + httppost.getRequestLine());
        response = httpclient.execute(httppost);

    } else {
        System.out.println("User has to be logged in to perform this function");
    }

    return response;
}

From source file:com.jelastic.JelasticService.java

DeployResponse deploy(AuthenticationResponse authentication, UploadResponse upLoader) {
    DeployResponse deployResponse = null;
    try {/*from w w  w.  jav  a2s .c o m*/
        DefaultHttpClient httpclient = getHttpClient();
        List<NameValuePair> qparams = new ArrayList<NameValuePair>();
        qparams.add(new BasicNameValuePair("charset", "UTF-8"));
        qparams.add(new BasicNameValuePair("session", authentication.getSession()));
        qparams.add(new BasicNameValuePair("archiveUri", upLoader.getFile()));
        qparams.add(new BasicNameValuePair("archiveName", upLoader.getName()));
        qparams.add(new BasicNameValuePair("newContext", getContext()));
        qparams.add(new BasicNameValuePair("domain", getEnvironment()));

        for (NameValuePair nameValuePair : qparams) {
            project.log(nameValuePair.getName() + " : " + nameValuePair.getValue(), Project.MSG_DEBUG);
        }

        URI uri = URIUtils.createURI(getProtocol(), getApiHoster(), getPort(), getUrlDeploy(),
                URLEncodedUtils.format(qparams, "UTF-8"), null);
        project.log("Deploy url : " + uri.toString(), Project.MSG_DEBUG);
        HttpGet httpPost = new HttpGet(uri);
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        String responseBody = httpclient.execute(httpPost, responseHandler);
        project.log("Deploy response : " + responseBody, Project.MSG_DEBUG);

        deployResponse = deserialize(responseBody, DeployResponse.class);
    } catch (URISyntaxException | IOException e) {
        project.log(e.getMessage(), Project.MSG_ERR);
    }
    return deployResponse;
}