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:model.web.ClientHttp.java

private String execute(List<NameValuePair> params) throws Exception {

    System.out.println("\nSending 'POST' request to URL : " + url);
    System.out.println("Post parameters : " + URLEncodedUtils.format(params, "utf-8"));

    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost(url + "?" + URLEncodedUtils.format(params, "utf-8"));

    // add header
    post.setHeader("charset", "UTF-8");
    post.setHeader("Content-Type", "application/json");

    HttpResponse response = client.execute(post);

    System.out.println("Response Code : " + response.getStatusLine().getStatusCode());

    BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

    StringBuffer result = new StringBuffer();
    String line = "";
    while ((line = rd.readLine()) != null) {
        result.append(line);/*from w  ww  .ja  va2 s  .co m*/
    }

    System.out.println("result: " + result.toString());
    return result.toString();
}

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

public HttpResponse addPost(String ticket, String target, String parentId, String textContent,
        String[] fileAttachments) throws URISyntaxException, ClientProtocolException, IOException {
    HttpPost httppost = null;//www .  j  a v  a  2 s  .  c  o  m
    if (fileAttachments == null) {
        List<NameValuePair> qparams = new ArrayList<NameValuePair>();
        qparams.add(new BasicNameValuePair("ticket", ticket));
        if (target != null)
            qparams.add(new BasicNameValuePair("target", target));
        else if (parentId != null) {
            qparams.add(new BasicNameValuePair("parentId", parentId));
        }
        qparams.add(new BasicNameValuePair("textContent", textContent));

        URI uri = URIUtils.createURI(scheme, host, port, appPath + "/api/2/ugc/" + "create.json",
                URLEncodedUtils.format(qparams, HTTP.UTF_8), null);
        httppost = new HttpPost(uri);
    } else {
        //if (fileAttachments!=null) {
        httppost = manageAttachments(fileAttachments, ticket, target, textContent);
        //}
    }

    HttpClient httpclient = new DefaultHttpClient();
    return httpclient.execute(httppost);

}

From source file:org.maikelwever.droidpile.backend.ApiConnecter.java

public String constructUrlQuery(String... kvs) {
    ArrayList<NameValuePair> args = new ArrayList<NameValuePair>();
    for (int i = 0; i < kvs.length; i = i + 2) {
        args.add(new BasicNameValuePair(
                //URLEncoder.encode(kvs[i], ENCODING),
                //URLEncoder.encode(kvs[i+1], ENCODING)
                kvs[i], kvs[i + 1]));//from w  w w. jav  a2  s. com
    }
    return URLEncodedUtils.format(args, ENCODING);
}

From source file:org.apache.sling.testing.tools.http.RequestBuilder.java

/** Build an URL from our base path, supplied path and optional
 *  query parameters.//from  ww  w.j  a  v a2s  . co m
 *  @param queryParameters an even number of Strings, each pair
 *  of values represents the key and value of a query parameter.
 *  Keys and values are encoded by this method.
 */
public String buildUrl(String path, String... queryParameters) {
    final StringBuilder sb = new StringBuilder();

    if (queryParameters == null || queryParameters.length == 0) {
        sb.append(baseUrl);
        sb.append(path);

    } else if (queryParameters.length % 2 != 0) {
        throw new IllegalArgumentException(
                "Invalid number of queryParameters arguments (" + queryParameters.length + "), must be even");
    } else {
        final List<NameValuePair> p = new ArrayList<NameValuePair>();
        for (int i = 0; i < queryParameters.length; i += 2) {
            p.add(new BasicNameValuePair(queryParameters[i], queryParameters[i + 1]));
        }
        sb.append(baseUrl);
        sb.append(path);
        sb.append("?");
        sb.append(URLEncodedUtils.format(p, "UTF-8"));
    }

    return sb.toString();
}

From source file:brooklyn.rest.BrooklynPropertiesSecurityFilterTest.java

@Test(groups = "Integration")
public void testInteractionOfSecurityFilterAndFormMapProvider() throws Exception {
    Stopwatch stopwatch = Stopwatch.createStarted();
    try {//from ww w .jav  a 2s  .  c om
        Server server = useServerForTest(
                BrooklynRestApiLauncher.launcher().securityProvider(AnyoneSecurityProvider.class)
                        .forceUseOfDefaultCatalogWithJavaClassPath(true).withoutJsgui().start());
        String appId = startAppAtNode(server);
        String entityId = getTestEntityInApp(server, appId);
        HttpClient client = HttpTool.httpClientBuilder().uri(getBaseUri(server)).build();
        List<? extends NameValuePair> nvps = Lists.newArrayList(new BasicNameValuePair("arg", "bar"));
        String effector = String.format("/v1/applications/%s/entities/%s/effectors/identityEffector", appId,
                entityId);
        HttpToolResponse response = HttpTool.httpPost(client, URI.create(getBaseUri() + effector),
                ImmutableMap.of(HttpHeaders.CONTENT_TYPE,
                        ContentType.APPLICATION_FORM_URLENCODED.getMimeType()),
                URLEncodedUtils.format(nvps, Charsets.UTF_8).getBytes());

        LOG.info("Effector response: {}", response.getContentAsString());
        assertTrue(HttpTool.isStatusCodeHealthy(response.getResponseCode()),
                "response code=" + response.getResponseCode());
    } finally {
        LOG.info("testInteractionOfSecurityFilterAndFormMapProvider complete in "
                + Time.makeTimeStringRounded(stopwatch));
    }
}

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

/**
 * @param fileName//from w w w. j  a v a  2s.  co  m
 * @throws IOException
 */
public void download(String fileName) throws IOException, MahasenClientException, URISyntaxException {
    httpclient = new DefaultHttpClient();
    OutputStream outputStream = null;

    ClientConfiguration clientConfiguration = ClientConfiguration.getInstance();

    try {
        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);

            List<NameValuePair> qparams = new ArrayList<NameValuePair>();
            qparams.add(new BasicNameValuePair("fileName", fileName));

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

            HttpPost httppost = new HttpPost(uri);

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

            if (httpEntity.getContentLength() > 0) {
                outputStream = new FileOutputStream(clientConfiguration.getDownloadRepo() + "/" + fileName);
                httpEntity.writeTo(outputStream);
            } else {
                System.out.println("no content available");
            }

            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            if (httpEntity != null) {
                System.out.println("Response content length: " + httpEntity.getContentLength());
                System.out.println("Chunked?: " + httpEntity.isChunked());
            }
            EntityUtils.consume(httpEntity);

            if (response.getStatusLine().getStatusCode() == 900) {
                throw new MahasenClientException(String.valueOf(response.getStatusLine()));
            }
        } else {
            System.out.println("User has to be logged in to perform this function");
        }
    } finally {
        httpclient.getConnectionManager().shutdown();
    }

}

From source file:com.madrobot.net.HttpTaskHelper.java

/**
 * Access point to add the query parameter to the request url
 * /*from  w ww  .j  a  va2s  . c  om*/
 * @throws URISyntaxException
 *             if request url syntax is wrong
 */
private void addQueryParameter() throws URISyntaxException {
    this.requestUrl = URIUtils.createURI(this.requestUrl.getScheme(), this.requestUrl.getAuthority(), -1,
            this.requestUrl.getPath(), URLEncodedUtils.format(requestParameter, HTTP.UTF_8), null);
}

From source file:org.jenkinsci.plugins.ownership.util.mail.MailFormatter.java

public @Nonnull String createMailToString(@CheckForNull List<String> to, @CheckForNull List<String> cc,
        @CheckForNull List<String> bcc, @CheckForNull String subject, @CheckForNull String body)
        throws UnsupportedEncodingException {
    StringBuilder b = new StringBuilder("mailto:");
    String toString = joinMailAddresses(to);
    if (toString != null) {
        b.append(URLEncoder.encode(toString, encoding));
    }/* ww  w  .j a  va2  s  .c  om*/
    List<NameValuePair> params = new LinkedList<NameValuePair>();
    joinMailAddresses(cc, "cc", params);
    joinMailAddresses(bcc, "bcc", params);
    if (subject != null) {
        params.add(new BasicNameValuePair("subject", subject));
    }
    if (body != null) {
        params.add(new BasicNameValuePair("body", body));
    }
    if (!params.isEmpty()) {
        b.append("?");
        String encodedParams = URLEncodedUtils.format(params, encoding);
        encodedParams = encodedParams.replace("+", "%20");
        b.append(encodedParams);
    }
    return b.toString();
}

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

/**
 * @param fileToUpdate//from w ww . j a  v  a 2  s.  c  o m
 * @param tags
 * @throws URISyntaxException
 * @throws AuthenticationExceptionException
 *
 * @throws IOException
 * @throws UnsupportedEncodingException
 */
public void updateMetadata(String fileToUpdate, String tags) throws URISyntaxException,
        AuthenticationExceptionException, IOException, UnsupportedEncodingException, MahasenClientException {

    httpclient = new DefaultHttpClient();
    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);

        // this will add file name and tags to user defined property list
        properties.add(new BasicNameValuePair("fileName", fileToUpdate));
        properties.add(new BasicNameValuePair("tags", tags));

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

        HttpPost httpPost = new HttpPost(uri);

        HttpResponse response = httpclient.execute(httpPost);
        HttpEntity resEntity = response.getEntity();

        System.out.println("----------------------------------------");
        System.out.println(response.getStatusLine());

        EntityUtils.consume(resEntity);
        if (response.getStatusLine().getStatusCode() == 900) {
            throw new MahasenClientException(String.valueOf(response.getStatusLine()));
        }

    }

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

    httpclient.getConnectionManager().shutdown();

}