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:org.craftercms.social.util.UGCHttpClient.java

public HttpResponse getTarget(String ticket, String target)
        throws URISyntaxException, ClientProtocolException, IOException {
    List<NameValuePair> qparams = new ArrayList<NameValuePair>();
    qparams.add(new BasicNameValuePair("ticket", ticket));
    qparams.add(new BasicNameValuePair("target", target));
    URI uri = URIUtils.createURI(scheme, host, port, appPath + "/api/2/ugc/target.json",
            URLEncodedUtils.format(qparams, HTTP.UTF_8), null);
    HttpGet httpget = new HttpGet(uri);
    HttpClient httpclient = new DefaultHttpClient();
    return httpclient.execute(httpget);
}

From source file:org.wso2.appcloud.integration.test.utils.clients.BaseClient.java

/**
 * 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.
 *
 * @param keyVal parameter map/*  w w  w.  j  av a 2  s  .c o  m*/
 * @return message body
 */
public String generateMsgBody(Map<String, String> keyVal) {
    List<NameValuePair> qparams = new ArrayList<NameValuePair>();
    for (Map.Entry<String, String> keyValEntry : keyVal.entrySet()) {
        qparams.add(new BasicNameValuePair(keyValEntry.getKey(), keyValEntry.getValue()));
    }
    return URLEncodedUtils.format(qparams, CharEncoding.UTF_8);
}

From source file:com.ovea.facebook.client.DefaultFacebookClient.java

private JSONType get(String proto, String host, String path, List<NameValuePair> qparams) {
    try {//ww w.  j  av  a 2s.com
        URI uri = URIUtils.createURI(proto, host, -1, path,
                qparams == null ? null : URLEncodedUtils.format(qparams, "UTF-8"), null);
        HttpResponse response = httpClient().execute(new HttpGet(uri));
        String contentType = response.getEntity().getContentType().getValue();
        contentType = contentType == null ? "" : contentType.toLowerCase();
        if (contentType.startsWith("application/json") || contentType.startsWith("text/javascript")) {
            return JSON.parse(EntityUtils.toString(response.getEntity()));
        } else {
            return JSON.object().put("data", EntityUtils.toString(response.getEntity()));
        }
    } catch (Exception e) {
        throw new FacebookException(e.getMessage(), e);
    }
}

From source file:com.nexmo.insight.sdk.NexmoInsightClient.java

public InsightResult request(final String number, final String callbackUrl, final String[] features,
        final long callbackTimeout, final String callbackMethod, final String clientRef, final String ipAddress)
        throws IOException, SAXException {
    if (number == null || callbackUrl == null)
        throw new IllegalArgumentException("number and callbackUrl parameters are mandatory.");
    if (callbackTimeout >= 0 && (callbackTimeout < 1000 || callbackTimeout > 30000))
        throw new IllegalArgumentException("callback timeout must be between 1000 and 30000.");

    log.debug("HTTP-Number-Insight Client .. to [ " + number + " ] ");

    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("number", number));
    params.add(new BasicNameValuePair("callback", callbackUrl));

    if (features != null)
        params.add(new BasicNameValuePair("features", strJoin(features, ",")));

    if (callbackTimeout >= 0)
        params.add(new BasicNameValuePair("callback_timeout", String.valueOf(callbackTimeout)));

    if (callbackMethod != null)
        params.add(new BasicNameValuePair("callback_method", callbackMethod));

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

    if (clientRef != null)
        params.add(new BasicNameValuePair("client_ref", clientRef));

    String inshightBaseUrl = this.baseUrl + PATH_INSIGHT;

    // 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.j a  v a2s .c o m*/
    for (int pass = 1; pass <= 2; pass++) {
        HttpPost httpPost = new HttpPost(inshightBaseUrl);
        httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
        HttpUriRequest method = httpPost;
        String url = inshightBaseUrl + "?" + 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 InsightResult(InsightResult.STATUS_COMMS_FAILURE, null, null, 0, 0,
                    "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 (!"lookup".equals(root.getNodeName()))
        throw new IOException("No valid response found [ " + response + "] ");

    return parseInsightResult(root);
}

From source file:io.servicecomb.serviceregistry.TestRegistry.java

@Test
public void testGetRealListenAddress() throws Exception {
    new Expectations(NetUtils.class) {
        {/*  w  ww. jav a 2  s. c  om*/
            NetUtils.getHostAddress();
            result = "1.1.1.1";
        }
    };

    Assert.assertEquals("rest://172.0.0.0:8080", RegistryUtils.getPublishAddress("rest", "172.0.0.0:8080"));
    Assert.assertEquals(null, RegistryUtils.getPublishAddress("rest", null));

    URI uri = new URI(RegistryUtils.getPublishAddress("rest", "0.0.0.0:8080"));
    Assert.assertEquals("1.1.1.1:8080", uri.getAuthority());

    new Expectations(DynamicPropertyFactory.getInstance()) {
        {
            DynamicPropertyFactory.getInstance().getStringProperty(PUBLISH_ADDRESS, "");
            result = new DynamicStringProperty(PUBLISH_ADDRESS, "") {
                public String get() {
                    return "1.1.1.1";
                }
            };
        }
    };
    Assert.assertEquals("rest://1.1.1.1:8080", RegistryUtils.getPublishAddress("rest", "172.0.0.0:8080"));

    InetAddress ethAddress = Mockito.mock(InetAddress.class);
    Mockito.when(ethAddress.getHostAddress()).thenReturn("1.1.1.1");
    new Expectations(DynamicPropertyFactory.getInstance()) {
        {
            NetUtils.ensureGetInterfaceAddress("eth20");
            result = ethAddress;
            DynamicPropertyFactory.getInstance().getStringProperty(PUBLISH_ADDRESS, "");
            result = new DynamicStringProperty(PUBLISH_ADDRESS, "") {
                public String get() {
                    return "{eth20}";
                }
            };
        }
    };
    String query = URLEncodedUtils.format(Arrays.asList(new BasicNameValuePair("country", " ")),
            StandardCharsets.UTF_8.name());
    Assert.assertEquals("rest://1.1.1.1:8080?" + query,
            RegistryUtils.getPublishAddress("rest", "172.0.0.0:8080?" + query));
}

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

protected String getDataTablePage(int aid) throws Exception {
    List<NameValuePair> params = addParameters(new ArrayList<NameValuePair>(), "aid", aid, "q", "r", "pagefrom",
            "BioAssaySummary", "acount", "0", "releasehold", "t", "activity" + aid, "");
    URI uri = URIUtils.createURI("http", SITE, 80, "/assay/assay.cgi", URLEncodedUtils.format(params, "UTF-8"),
            null);//from w  w w . j ava 2s .c o  m
    return new WaitOnRequestId(uri).asPage();
}

From source file:org.cloudsmith.stackhammer.api.client.StackHammerClient.java

/**
 * Executes a HTTP GET request. The http response is expected to be a JSON representation of
 * an object of the specified <code>type</code>. The object is parsed and returned.
 * //from w w w .  j  a  v a2  s.  co  m
 * @param urlStr The URL of the request
 * @param params Parameters to include in the URL
 * @param type The expected type of the result
 * @return An object of the expected type
 * @throws IOException if the request could not be completed
 */
public <V> V get(String urlStr, Map<String, String> params, Class<V> type) throws IOException {
    URI uri;
    try {
        uri = new URI(createUri(urlStr));
        if (params != null && !params.isEmpty()) {
            List<NameValuePair> queryParams = new ArrayList<NameValuePair>(params.size());
            for (Map.Entry<String, String> param : params.entrySet())
                queryParams.add(new BasicNameValuePair(param.getKey(), param.getValue()));

            uri = URIUtils.createURI(uri.getScheme(), uri.getHost(), uri.getPort(), uri.getPath(),
                    URLEncodedUtils.format(queryParams, UTF_8.name()), uri.getFragment());
        }
    } catch (URISyntaxException e) {
        throw new IllegalArgumentException(e);
    }

    HttpGet request = new HttpGet(uri);
    configureRequest(request);
    return executeRequest(request, type);
}

From source file:com.siddroid.offlinews.SendOffline.java

/**
 * Send get./* www.  j ava  2  s .  c  o  m*/
 * This function sends a Get request to webservice
 * @param url the url url of webservice
 * @param req the req for the webservice
 * @return the result as object
 */
public Object sendGet(String url, String req) {
    /*encode request data using nameValue pairs*/
    String paramString = URLEncodedUtils.format(getNameValuePaires(req), HTTP.UTF_8);
    /*combine url and parameters*/
    url += "?" + paramString;
    HttpGet request = new HttpGet(url);
    DefaultHttpClient client = new DefaultHttpClient();
    InputStream source = fetchResponse(request, client);
    /*returns result object after processing inputstream*/
    return sendResponse(source);
}

From source file:com.janoz.usenet.processors.impl.WebbasedProcessor.java

private URI constructURI(String command, List<NameValuePair> fields) throws IOException {

    try {//from w w  w  .  ja v a  2  s  .c  o  m
        String url = (((rootDir == null) || (rootDir.length() == 0)) ? "" : "/" + rootDir) + "/" + command;
        String params = null;
        if (fields != null) {
            params = URLEncodedUtils.format(fields, "UTF-8");
        }
        return URIUtils.createURI(serverProtocol, serverAddress, serverPort, url, params, null);
    } catch (URISyntaxException e) {
        throw new IOException(e);
    }
}

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

/**
 * @param propertyName//from   w  ww  .  ja v  a  2  s.  c om
 * @param isRangeBase
 * @param value1
 * @param value2
 * @param hostIP
 * @return
 * @throws IOException
 * @throws URISyntaxException
 * @throws AuthenticationExceptionException
 *
 * @throws MahasenClientException
 */
private HttpResponse sendRequest(String propertyName, boolean isRangeBase, String value1, String value2,
        String hostIP)
        throws IOException, URISyntaxException, AuthenticationExceptionException, MahasenClientException {

    httpclient = new DefaultHttpClient();
    clientLogin = new ClientLogin();
    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");
    }

    if (response.getStatusLine().getStatusCode() == 900) {
        throw new MahasenClientException(String.valueOf(response.getStatusLine()));
    } else if (response.getStatusLine().getStatusCode() == 901) {
        throw new MahasenClientException(String.valueOf(response.getStatusLine()));
    }

    return response;
}