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:com.cr_wd.android.network.HttpParams.java

public String getParamString() {
    return URLEncodedUtils.format(getParamsList(), encoding);
}

From source file:org.opencastproject.remotetest.server.EpisodeServiceTest.java

private Document doGetRequest(String path, int expectedHttpResonseCode, Tuple<String, ?>... params) {
    List<NameValuePair> qparams = new ArrayList<NameValuePair>();
    for (Tuple<String, ?> p : params) {
        qparams.add(new BasicNameValuePair(p.getA(), p.getB().toString()));
    }//from  w  w w. j a v  a 2 s  .c  o  m
    String query = URLEncodedUtils.format(qparams, "UTF-8");
    final String url = baseUrl + (path.startsWith("/") ? path : "/" + path)
            + (StringUtils.isNotEmpty(query) ? "?" + query : "");

    HttpGet get = new HttpGet(url);
    HttpResponse response = client.execute(get);
    assertEquals(expectedHttpResonseCode, response.getStatusLine().getStatusCode());
    if (expectedHttpResonseCode != HttpStatus.SC_NO_CONTENT)
        return getXml(response);
    else
        return null;
}

From source file:com.brightcove.com.uploader.helper.MediaAPIHelper.java

/**
 * Executes a media read api call against a given server.
 * @param server application server you want to execute against
 * @param port port number api servlet is listening on
 * @param parameters query parameters representing the read api call
 * @return json response from api/*w  w w. ja  v  a2  s.com*/
 * @throws URISyntaxException
 * @throws MediaAPIError
 */
public JsonNode executeRead(String server, int port, List<NameValuePair> parameters)
        throws URISyntaxException, MediaAPIError {
    mLog.debug("using " + server + " on port " + port + " for api read");

    URI commandUrl = URIUtils.createURI("http", server, port, "services/library",
            URLEncodedUtils.format(parameters, "UTF-8"), null);

    // Make the request
    HttpGet httpGet = new HttpGet(commandUrl);
    return executeCall(httpGet);
}

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

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

From source file:org.jboss.shrinkwrap.jetty_7.test.JettyDeploymentIntegrationUnitTestCase.java

/**
 * Tests that we can execute an HTTP request and it's fulfilled as expected, 
 * proving our deployment succeeded// w  ww .  j a va  2  s  .  c  o  m
 */
@Test
public void requestWebapp() throws Exception {
    // Get an HTTP Client
    final HttpClient client = new DefaultHttpClient();

    // Make an HTTP Request, adding in a custom parameter which should be echoed back to us
    final String echoValue = "ShrinkWrap>Jetty 7 Integration";
    final List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("to", PATH_ECHO_SERVLET));
    params.add(new BasicNameValuePair("echo", echoValue));
    final URI uri = URIUtils.createURI("http", HTTP_BIND_HOST, HTTP_BIND_PORT,
            NAME_WEBAPP + SEPARATOR + forwardingServletClass.getSimpleName(),
            URLEncodedUtils.format(params, "UTF-8"), null);
    final HttpGet request = new HttpGet(uri);

    // Execute the request
    log.info("Executing request to: " + request.getURI());
    final HttpResponse response = client.execute(request);
    System.out.println(response.getStatusLine());
    final HttpEntity entity = response.getEntity();
    if (entity == null) {
        Assert.fail("Request returned no entity");
    }

    // Read the result, ensure it's what we're expecting (should be the value of request param "echo")
    final BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent()));
    final String line = reader.readLine();
    Assert.assertEquals("Unexpected response from Servlet", echoValue, line);

}

From source file:eu.masconsult.bgbanking.banks.sgexpress.SGExpressClient.java

private void performAuthentication(DefaultHttpClient httpClient, AuthToken authToken)
        throws IOException, AuthenticationException {
    HttpResponse resp;/*  w  ww .  java  2  s.c om*/
    final ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair(PARAM_USERNAME, authToken.username));
    params.add(new BasicNameValuePair(PARAM_PASSWORD, authToken.password));
    params.add(new BasicNameValuePair(PARAM_USER_TIME, "dummy"));
    final HttpEntity entity;
    try {
        entity = new UrlEncodedFormEntity(params);
    } catch (final UnsupportedEncodingException e) {
        // this should never happen.
        throw new IllegalStateException(e);
    }
    String uri = BASE_URL + "?"
            + URLEncodedUtils.format(Arrays.asList(new BasicNameValuePair(XML_ID, AUTH_XML_ID)), ENCODING);
    Log.i(TAG, "Authenticating to: " + uri);

    final HttpPost post = new HttpPost(uri);
    post.addHeader(entity.getContentType());
    post.setHeader("Accept", "*/*");
    post.setEntity(entity);
    resp = httpClient.execute(post);

    // check for bad status
    if (resp.getStatusLine().getStatusCode() != HttpStatus.SC_MOVED_TEMPORARILY) {
        throw new ParseException("status after auth: " + resp.getStatusLine().getStatusCode() + " "
                + resp.getStatusLine().getReasonPhrase());
    }

    // check header redirect
    Header[] locations = resp.getHeaders(HEADER_LOCATION);
    if (locations.length != 1) {
        throw new ParseException(locations.length + " header locations received!");
    }

    String location = "https://" + DOMAIN + locations[0].getValue();
    Log.v(TAG, "location=" + location);

    UrlQuerySanitizer sanitizer = new UrlQuerySanitizer(location);
    authToken.userId = sanitizer.getValue(PARAM_USER_ID);
    authToken.sessionId = sanitizer.getValue(PARAM_SESSION_ID);
    String redirectedXmlId = sanitizer.getValue(XML_ID);

    if (authToken.userId == null || authToken.userId.length() == 0 || authToken.sessionId == null
            || authToken.sessionId.length() == 0 || AUTH_XML_ID.equalsIgnoreCase(redirectedXmlId)) {
        checkAuthError(sanitizer);
    }
}

From source file:com.brightcove.zartan.common.helper.MediaAPIHelper.java

/**
 * Executes a media read api call against a given server.
 * // w w  w  .  ja v a 2s . c  o m
 * @param server application server you want to execute against
 * @param port port number api servlet is listening on
 * @param parameters query parameters representing the read api call
 * @return json response from api
 * @throws URISyntaxException
 * @throws MediaAPIException
 */
public JsonNode executeRead(String server, int port, List<NameValuePair> parameters)
        throws URISyntaxException, MediaAPIException {
    mLog.debug("using " + server + " on port " + port + " for api read");

    URI commandUrl = URIUtils.createURI("http", server, port, "services/library",
            URLEncodedUtils.format(parameters, "UTF-8"), null);

    // Make the request
    HttpGet httpGet = new HttpGet(commandUrl);
    return executeCall(httpGet);
}

From source file:com.cellobject.oikos.util.NetworkHelper.java

/**
 * Sends HTTP GET request and returns body of response from server as HTTPResponse object. The response object contains HTTP
 * headers and body. This method also writes both header and body to log. Use LogCat to view output. Also notice that in this
 * case the body is read line by line from a stream (in.readLine()). In most cases one of the above methods should suffice.
 *///from   ww w .j a v  a2s  .  c  o m
public HttpResponse httpGetWithHeader(final String urlToServer, final List<BasicNameValuePair> parameterList)
        throws IOException {
    final String url = urlToServer + "?" + URLEncodedUtils.format(parameterList, null);
    BufferedReader in = null;
    try {
        final HttpGet request = new HttpGet(url);
        final HttpResponse response = client.execute(request);
        /* Let's get/log the HTTP-header * */
        final Header[] headers = response.getAllHeaders();
        for (final Header h : headers) {
            Log.i("HTTPHEADER", "Header names: " + h.getName());
            Log.i("HTTPHEADER", "Header Value: " + h.getValue());
        }
        /* Read body of HTTP-message from server */
        in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        final StringBuffer body = new StringBuffer("");
        String line = null;
        while ((line = in.readLine()) != null) {
            body.append(line + "\n");
            Log.i("HTTPBODY", line);
        }
        return response;
    } finally {
        try {
            in.close();
        } catch (final IOException ie) {
            Log.e("HTTP", ie.toString());
        }
    }
}

From source file:com.mgmtp.perfload.core.client.web.request.HttpRequestHandler.java

/**
 * Creates the request object./*from   ww  w. jav a  2  s.c o m*/
 * 
 * @param type
 *            the type of the HTTP request (GET, TRACE, DELETE, OPTIONS, HEAD, POST, PUT)
 * @param uri
 *            the uri
 * @param parameters
 *            the request parameters
 * @param body
 *            the request body
 * @return the request
 */
protected HttpRequestBase createRequest(final String type, final URI uri, final List<NameValuePair> parameters,
        final Body body) throws Exception {
    HttpRequestBase request = HttpMethod.valueOf(type).create(uri);
    if (!(request instanceof HttpEntityEnclosingRequest)) {
        //  GET, TRACE, DELETE, OPTIONS, HEAD
        if (!parameters.isEmpty()) {
            String query = URLEncodedUtils.format(parameters, "UTF-8");
            URI requestURI = new URI(
                    uri.getRawQuery() == null ? uri.toString() + '?' + query : uri.toString() + '&' + query);
            request.setURI(requestURI);
        }
    } else {
        // POST, PUT
        final HttpEntityEnclosingRequest entityRequest = (HttpEntityEnclosingRequest) request;
        if (body != null) {
            // this only sets the content, header come from the request flow
            entityRequest.setEntity(new ByteArrayEntity(body.getContent()));
        } else {
            checkState(request instanceof HttpPost, "Invalid request: " + request.getMethod()
                    + ". Cannot add post parameters to this kind of request. Please check the request flow.");
            entityRequest.setEntity(new UrlEncodedFormEntity(parameters, "UTF-8"));
        }
    }
    return request;
}

From source file:com.puppetlabs.puppetdb.javaclient.impl.HttpComponentsConnector.java

private HttpGet createGetRequest(String urlStr, Map<String, String> params) {
    StringBuilder bld = new StringBuilder(createURI(urlStr));
    if (params != null && !params.isEmpty()) {
        List<BasicNameValuePair> pairs = new ArrayList<BasicNameValuePair>();
        for (Map.Entry<String, String> param : params.entrySet())
            pairs.add(new BasicNameValuePair(param.getKey(), param.getValue()));
        bld.append('?');
        bld.append(URLEncodedUtils.format(pairs, UTF_8.name()));
    }//from   w  ww.j  a v  a  2s  . c o m
    return new HttpGet(URI.create(bld.toString()));
}