Example usage for org.apache.http.client.entity UrlEncodedFormEntity UrlEncodedFormEntity

List of usage examples for org.apache.http.client.entity UrlEncodedFormEntity UrlEncodedFormEntity

Introduction

In this page you can find the example usage for org.apache.http.client.entity UrlEncodedFormEntity UrlEncodedFormEntity.

Prototype

public UrlEncodedFormEntity(final Iterable<? extends NameValuePair> parameters, final Charset charset) 

Source Link

Document

Constructs a new UrlEncodedFormEntity with the list of parameters in the specified encoding.

Usage

From source file:com.googlecode.noweco.webmail.portal.lotuslive.LotusLivePortalConnector.java

public PortalConnection connect(final HttpHost proxy, final String user, final String password)
        throws IOException {
    DefaultHttpClient httpclient = UnsecureHttpClientFactory.INSTANCE.createUnsecureHttpClient(proxy);

    HttpGet httpGet;//from  www .j a  v a 2s.c o  m
    HttpPost httpost;
    HttpResponse rsp;
    HttpEntity entity;

    // STEP 1 : Login page

    httpGet = new HttpGet("https://apps.lotuslive.com/manage/account/dashboardHandler/input");
    rsp = httpclient.execute(httpGet);

    entity = rsp.getEntity();
    if (entity != null) {
        EntityUtils.consume(entity);
    }

    // STEP 2 : Send form

    // prepare the request
    httpost = new HttpPost("https://apps.lotuslive.com/pkmslogin.form");
    List<NameValuePair> nvps = new ArrayList<NameValuePair>();
    nvps.add(new BasicNameValuePair("login-form-type", "pwd"));
    nvps.add(new BasicNameValuePair("username", user));
    nvps.add(new BasicNameValuePair("password", password));
    httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));

    // send the request
    rsp = httpclient.execute(httpost);

    // free result resources
    entity = rsp.getEntity();
    if (entity != null) {
        EntityUtils.consume(entity);
    }

    int statusCode = rsp.getStatusLine().getStatusCode();
    if (statusCode != 302) {
        throw new IOException("Unable to connect to lotus live portail, status code : " + statusCode);
    }

    // STEP 3 : Fetch SAML token

    httpGet = new HttpGet("https://mail.lotuslive.com/mail/loginlanding");
    rsp = httpclient.execute(httpGet);

    entity = rsp.getEntity();
    String firstEntity = EntityUtils.toString(entity);
    if (entity != null) {
        EntityUtils.consume(entity);
    }

    // STEP 4 : Use SAML token to identify

    httpost = new HttpPost("https://mail.lotuslive.com/auth/tfim");
    nvps = new ArrayList<NameValuePair>();
    nvps.add(new BasicNameValuePair("TARGET", "http://mail.lotuslive.com/mail"));
    Matcher samlMatcher = SAML_RESPONSE.matcher(firstEntity);
    if (!samlMatcher.find()) {
        throw new IOException("Unable to find SAML token");
    }
    nvps.add(new BasicNameValuePair("SAMLResponse", samlMatcher.group(1)));

    httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
    // send the request
    rsp = httpclient.execute(httpost);

    entity = rsp.getEntity();
    if (entity != null) {
        EntityUtils.consume(entity);
    }

    // STEP 5 : VIEW ROOT PAGE (TODO can delete ?)

    httpGet = new HttpGet("https://mail-usw.lotuslive.com/mail/mail/listing/INBOX");
    rsp = httpclient.execute(httpGet);

    entity = rsp.getEntity();
    if (entity != null) {
        EntityUtils.consume(entity);
    }

    return new DefaultPortalConnection(httpclient, new HttpHost("mail-usw.lotuslive.com", 443), "");
}

From source file:dk.i2m.drupal.util.HttpMessageBuilder.java

/**
 * Turn this HttpMessageBuilder object into a {@link UrlEncodedFormEntity}.
 * /*from  w  w  w.  j a  v a  2 s. c o  m*/
 * @return  a new UrlEncodedFormEntity object
 */
public UrlEncodedFormEntity toUrlEncodedFormEntity() {
    return new UrlEncodedFormEntity(prep(), Consts.UTF_8);
}

From source file:org.codeqinvest.web.IntegrationTestHelper.java

private static void doPostRequest(String uri, List<NameValuePair> parameters) throws IOException {
    HttpClient httpClient = new DefaultHttpClient();
    HttpPost post = new HttpPost(uri);
    post.setEntity(new UrlEncodedFormEntity(parameters, Consts.UTF_8));
    httpClient.execute(post);//  w w w.  j a  v  a 2 s.c o m
}

From source file:kindleclippings.quizlet.QuizletAPI.java

private HttpResponse post(String path, List<? extends NameValuePair> params)
        throws ClientProtocolException, IOException {
    HttpPost post = new HttpPost("https://api.quizlet.com/2.0" + path);
    post.addHeader("Authorization", "Bearer " + accessToken);
    post.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
    return new DefaultHttpClient().execute(post);
}

From source file:org.opencastproject.remotetest.server.perf.ConcurrentWorkflowTest.java

@Test
@PerfTest(invocations = 100, threads = 100)
public void testStartAndRetrieveWorkflowInstance() throws Exception {
    // Start a workflow instance via the rest endpoint
    HttpPost postStart = new HttpPost(BASE_URL + "/workflow/start");
    List<NameValuePair> formParams = new ArrayList<NameValuePair>();

    formParams.add(new BasicNameValuePair("definition", getSampleWorkflowDefinition()));
    formParams.add(new BasicNameValuePair("mediapackage", getSampleMediaPackage()));
    formParams.add(new BasicNameValuePair("properties", "this=that"));
    postStart.setEntity(new UrlEncodedFormEntity(formParams, "UTF-8"));

    // Grab the new workflow instance from the response
    String postResponse = EntityUtils.toString(client.execute(postStart).getEntity());
    String id = getWorkflowInstanceId(postResponse);

    // Ensure we can retrieve the workflow instance from the rest endpoint
    HttpGet getWorkflowMethod = new HttpGet(BASE_URL + "/workflow/instance/" + id + ".xml");
    String getResponse = EntityUtils.toString(client.execute(getWorkflowMethod).getEntity());
    Assert.assertEquals(id, getWorkflowInstanceId(getResponse));

    // Make sure we can retrieve it via json, too
    HttpGet getWorkflowJson = new HttpGet(BASE_URL + "/workflow/instance/" + id + ".json");
    String jsonResponse = EntityUtils.toString(client.execute(getWorkflowJson).getEntity());
    JSONObject json = (JSONObject) JSONValue.parse(jsonResponse);
    if (json == null)
        Assert.fail("JSON response should not be null, but is " + jsonResponse);
    Assert.assertEquals(id, json.get("workflow_id"));

    // Ensure that the workflow finishes successfully
    int attempts = 0;
    while (true) {
        if (++attempts == 1000)
            Assert.fail("workflow rest endpoint test has hung");
        getWorkflowMethod = new HttpGet(BASE_URL + "/workflow/instance/" + id + ".xml");
        getResponse = EntityUtils.toString(client.execute(getWorkflowMethod).getEntity());
        String state = getWorkflowInstanceStatus(getResponse);
        if ("FAILED".equals(state))
            Assert.fail("workflow instance " + id + " failed");
        if ("SUCCEEDED".equals(state))
            break;
        System.out.println("workflow " + id + " is " + state);
        Thread.sleep(5000);//from  w ww.  j ava  2  s . co  m
    }
}

From source file:de.unistuttgart.ipvs.pmp.apps.vhike.tools.JSonRequestProvider.java

/**
 * Sending a request to the WEBSERVICE_URL defined in {@link Constants}
 * /* ww  w  .jav a  2 s .  c o m*/
 * @param listToParse
 *            contains all the parameters, which have to be parsed
 * @param url
 * @param debug
 *            mode true or false
 * @return JsonObject
 * @throws IOException
 * @throws ClientProtocolException
 */
public static JsonObject doRequest(List<ParamObject> listToParse, String url)
        throws ClientProtocolException, IOException {

    // GET REQUESTS
    StringBuffer buf = new StringBuffer();
    buf.append(url);
    buf.append("?");

    for (ParamObject object : listToParse) {

        if (!(object.isPost())) {
            buf.append(object.getKey() + "=" + object.getValue());
            buf.append("&");
            // getParam = getParam + object.getKey() + "=" +
            // object.getValue();
            // getParam = getParam + "&";
        }
    }
    String getParam = buf.toString();
    // Cut the last '&' out
    getParam = getParam.substring(0, getParam.length() - 1);

    Log.d(TAG, "Param: " + getParam);

    // Create a new HttpClient and Post Header
    HttpClient httpclient = new DefaultHttpClient();

    HttpPost httppost = new HttpPost(Constants.WEBSERVICE_URL + getParam);

    List<NameValuePair> namelist = new ArrayList<NameValuePair>(listToParse.size());

    // Iterate over objects, which have to be post to the web service
    // POST REQUESTS
    for (ParamObject object : listToParse) {
        if ((object.isPost())) {
            namelist.add(new BasicNameValuePair(object.getKey(), object.getValue()));
            // TODO: Remove this line
            Log.d(TAG, "POST: " + object.getKey() + " - " + object.getValue());
        }
    }

    httppost.setEntity(new UrlEncodedFormEntity(namelist, "UTF-8"));

    // Execute HTTP Post Request
    HttpResponse response;
    JsonObject jsonObject = null;
    response = httpclient.execute(httppost);
    // for JSON:
    if (response != null) {
        InputStream is = response.getEntity().getContent();
        BufferedReader r = new BufferedReader(new InputStreamReader(is));
        try {
            StringBuffer sb = new StringBuffer();
            String s = null;
            while ((s = r.readLine()) != null) {
                sb.append(s).append(System.getProperty("line.separator"));
            }
            s = sb.toString();

            jsonObject = (new JsonParser()).parse(s).getAsJsonObject();
            Log.d(TAG, "======DEBUG=====");
            Log.d(TAG, s);
            Log.d(TAG, "======DEBUG=====");
        } catch (Exception e) {
            Log.d(TAG, e.getMessage());
        }
    } else {
        Log.d(TAG, "No Response");
    }
    return jsonObject;
}

From source file:org.blanco.techmun.android.cproviders.ComentariosFetcher.java

public FetchComentariosResult fetchComentarios(Long eventoId, Integer pagina) {
    FetchComentariosResult result = new FetchComentariosResult();
    HttpPost request = new HttpPost(
            TechMunContentProvider.MESAS_REST_SERVICE_BSAE_URI + "/comentarios/" + eventoId);
    HttpResponse response = null;//from  w  w w  . jav  a 2s.co  m
    try {
        //prepare the entity for the request
        List<BasicNameValuePair> parameters = new ArrayList<BasicNameValuePair>();
        parameters.add(new BasicNameValuePair("eventoId", eventoId.toString()));
        parameters.add(new BasicNameValuePair("pagina", pagina.toString()));
        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parameters, "utf-8");
        request.setEntity(entity);

        response = httpClient.execute(request);
        if (response.getStatusLine().getStatusCode() == 200) {
            Comentarios comentarios = new Comentarios();

            //The response return a Json object with the next page available for the net fetch and the selected objects
            JSONObject jsonComents = XmlParser.parseJSONObjectFromHttpEntity(response.getEntity());
            pagina = jsonComents.getInt("pagina");
            boolean mas = jsonComents.getBoolean("mas");
            JSONArray coments = jsonComents.getJSONArray("comentarios");
            for (int i = 0; i < coments.length(); i++) {
                long id = coments.getJSONObject(i).getLong("id");
                String comentario = coments.getJSONObject(i).getString("comentario");
                String autor = "";
                if (coments.getJSONObject(i).has("autor")) {
                    autor = coments.getJSONObject(i).getString("autor");
                }
                String contacto = "";
                if (coments.getJSONObject(i).has("contacto")) {
                    contacto = coments.getJSONObject(i).getString("contacto");
                }
                Date fecha = new Date(Date.parse(coments.getJSONObject(i).getString("fecha")));
                Comentario c = new Comentario();
                c.setId(id);
                c.setAutor(autor);
                c.setComentario(comentario);
                c.setContacto(contacto);
                c.setFecha(fecha);
                //if all the parsing went well add the new object to the results
                comentarios.addComentario(c);
            }
            //Prepare the result
            result.comentarios = comentarios;
            result.pagina = pagina;
            result.mas = mas;
        }
    } catch (Exception ex) {
        Log.e("techmun", "Error posting comentario", ex);
    }
    return result;

}

From source file:com.mashape.unirest.request.body.MultipartBody.java

public HttpEntity getEntity() {
    if (hasFile) {
        MultipartEntity entity = new MultipartEntity();
        for (Entry<String, Object> part : parameters.entrySet()) {
            if (part.getValue() instanceof File) {
                hasFile = true;//from ww  w  .  j a  v  a  2 s  .c  om
                entity.addPart(part.getKey(), new FileBody((File) part.getValue()));
            } else {
                try {
                    entity.addPart(part.getKey(),
                            new StringBody(part.getValue().toString(), Charset.forName(UTF_8)));
                } catch (UnsupportedEncodingException e) {
                    throw new RuntimeException(e);
                }
            }
        }
        return entity;
    } else {
        try {
            return new UrlEncodedFormEntity(MapUtil.getList(parameters), UTF_8);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }
}

From source file:com.samebug.clients.search.api.client.SamebugClient.java

public @NotNull ClientResponse<SearchResults> searchSolutions(@NotNull final String stacktrace) {
    final URL url = urlBuilder.search();
    HttpPost post = new HttpPost(url.toString());
    post.setEntity(new UrlEncodedFormEntity(
            Collections.singletonList(new BasicNameValuePair("exception", stacktrace)), Consts.UTF_8));

    return rawClient.execute(post, new HandleAuthenticatedJsonRequest<SearchResults>(SearchResults.class));
}

From source file:network.thunder.client.communications.HTTPS.java

public void submitPOST() throws ClientProtocolException, IOException {
    httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
    httpResponse = httpClient.execute(httpPost);
}