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) 

Source Link

Document

Constructs a new UrlEncodedFormEntity with the list of parameters with the default encoding of HTTP#DEFAULT_CONTENT_CHARSET

Usage

From source file:com.sampullara.findmyiphone.FindMyDevice.java

private static void writeDeviceLocations(Writer out, String username, String password) throws IOException {
    // Initialize the HTTP client
    DefaultHttpClient hc = new DefaultHttpClient();

    // Authorize with Apple's mobile me service
    HttpGet auth = new HttpGet(
            "https://auth.apple.com/authenticate?service=DockStatus&realm=primary-me&formID=loginForm&username="
                    + username + "&password=" + password
                    + "&returnURL=aHR0cHM6Ly9zZWN1cmUubWUuY29tL3dvL1dlYk9iamVjdHMvRG9ja1N0YXR1cy53b2Evd2EvdHJhbXBvbGluZT9kZXN0aW5hdGlvblVybD0vYWNjb3VudA%3D%3D");
    hc.execute(auth);//  w  w w  .j a  v  a 2  s.  c om
    auth.abort();

    // Pull the isc-secure.me.com cookie out so we can set the X-Mobileme-Isc header properly
    String isc = extractIscCode(hc);

    // Get access to the devices and find out their ids
    HttpPost devicemgmt = new HttpPost("https://secure.me.com/wo/WebObjects/DeviceMgmt.woa/?lang=en");
    devicemgmt.addHeader("X-Mobileme-Version", "1.0");
    devicemgmt.addHeader("X-Mobileme-Isc", isc);
    devicemgmt.setEntity(new UrlEncodedFormEntity(new ArrayList<NameValuePair>()));
    HttpResponse devicePage = hc.execute(devicemgmt);

    // Extract the device ids from their html encoded in json
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    devicePage.getEntity().writeTo(os);
    os.close();
    Matcher m = Pattern.compile("DeviceMgmt.deviceIdMap\\['[0-9]+'\\] = '([a-z0-9]+)';")
            .matcher(new String(os.toByteArray()));
    List<String> deviceList = new ArrayList<String>();
    while (m.find()) {
        deviceList.add(m.group(1));
    }

    // For each available device, get the location
    JsonFactory jf = new JsonFactory();
    JsonGenerator jg = jf.createJsonGenerator(out);
    jg.writeStartObject();
    for (String device : deviceList) {
        HttpPost locate = new HttpPost(
                "https://secure.me.com/wo/WebObjects/DeviceMgmt.woa/wa/LocateAction/locateStatus");
        locate.addHeader("X-Mobileme-Version", "1.0");
        locate.addHeader("X-Mobileme-Isc", isc);
        locate.setEntity(new StringEntity(
                "postBody={\"deviceId\": \"" + device + "\", \"deviceOsVersion\": \"7A341\"}"));
        locate.setHeader("Content-type", "application/json");
        HttpResponse location = hc.execute(locate);
        InputStream inputStream = location.getEntity().getContent();
        JsonParser jp = jf.createJsonParser(inputStream);
        jp.nextToken(); // ugly
        jg.writeFieldName(device);
        jg.copyCurrentStructure(jp);
        inputStream.close();
    }
    jg.close();
    out.close();
}

From source file:att.jaxrs.client.Webinar.java

public static String updateWebinar(Webinar webinar) {
    List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
    urlParameters.add(new BasicNameValuePair("content_id", webinar.getContent_id().toString()));
    urlParameters.add(new BasicNameValuePair("presenter", webinar.getPresenter()));

    String resultStr = "";

    try {/* w w  w . ja va  2 s.  c o m*/

        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost post = new HttpPost(Constants.UPDATE_WEBINAR_RESOURCE);
        post.setEntity(new UrlEncodedFormEntity(urlParameters));
        HttpResponse result = httpClient.execute(post);
        System.out.println(Constants.RESPONSE_STATUS_CODE + result);
        resultStr = Util.getStringFromInputStream(result.getEntity().getContent());
        System.out.println(Constants.RESPONSE_BODY + resultStr);

    } catch (Exception e) {
        System.out.println(e.getMessage());

    }
    return resultStr;
}

From source file:com.zazuko.blv.outbreak.tools.SparqlClient.java

List<Map<String, RDFTerm>> queryResultSet(final String query) throws IOException {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpPost httpPost = new HttpPost(endpoint);
    List<NameValuePair> nvps = new ArrayList<NameValuePair>();
    nvps.add(new BasicNameValuePair("query", query));
    httpPost.setEntity(new UrlEncodedFormEntity(nvps));
    CloseableHttpResponse response2 = httpclient.execute(httpPost);

    try {//from w  w  w.  j av  a  2 s  .  c  om
        HttpEntity entity2 = response2.getEntity();
        InputStream in = entity2.getContent();
        SAXParserFactory spf = SAXParserFactory.newInstance();
        spf.setNamespaceAware(true);
        SAXParser saxParser = spf.newSAXParser();
        XMLReader xmlReader = saxParser.getXMLReader();
        final SparqlsResultsHandler sparqlsResultsHandler = new SparqlsResultsHandler();
        xmlReader.setContentHandler(sparqlsResultsHandler);
        xmlReader.parse(new InputSource(in));
        /*
         for (int ch = in.read(); ch != -1; ch = in.read()) {
         System.out.print((char)ch);
         }
         */
        // do something useful with the response body
        // and ensure it is fully consumed
        EntityUtils.consume(entity2);
        return sparqlsResultsHandler.getResults();
    } catch (ParserConfigurationException ex) {
        throw new RuntimeException(ex);
    } catch (SAXException ex) {
        throw new RuntimeException(ex);
    } finally {
        response2.close();
    }

}

From source file:org.sigmond.net.HttpUtils.java

public void doPost(String url, Map<String, String> params, HttpCallback callback) {
    try {/*w  w w  .  j  a  v  a  2  s  . c  o m*/

        HttpPost post = new HttpPost(url);

        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(params.size());

        for (String key : params.keySet()) {
            nameValuePairs.add(new BasicNameValuePair(key, params.get(key)));
        }

        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(nameValuePairs);
        post.setEntity(entity);

        HttpRequestInfo rinfo = new HttpRequestInfo(post, callback);
        rinfo.setParams(params);
        rinfo.setCookieStore(cookies);
        AsyncHttpTask task = new AsyncHttpTask();
        task.execute(rinfo);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.eclipse.mylyn.internal.hudson.core.client.HudsonRunBuildForm.java

public UrlEncodedFormEntity createEntity() throws UnsupportedEncodingException {
    Parameters jsonObject = new Parameters();
    jsonObject.parameter = params.toArray(new NameValue[0]);

    // set json encoded entities
    requestParameters.add(new BasicNameValuePair("json", new Gson().toJson(jsonObject))); //$NON-NLS-1$

    // set form parameters
    requestParameters.add(new BasicNameValuePair("Submit", "Build"));

    // create entity
    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(requestParameters);
    return entity;
}

From source file:dario.androidclient.HttpPostTaskSample.java

@Override
protected String doInBackground(String... params) {
    BufferedReader inBuffer = null;
    String url = params[0];// w  ww  .  java2s .  c om
    String result;
    try {
        HttpClient httpClient = new DefaultHttpClient();
        HttpPost request = new HttpPost(url);
        List<NameValuePair> postParameters = new ArrayList<NameValuePair>();
        postParameters.add(new BasicNameValuePair("textToEcho", params[1]));

        UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);

        request.setEntity(formEntity);
        HttpResponse response = httpClient.execute(request);
        if (response != null) {
            result = EntityUtils.toString(response.getEntity());
        } else {
            result = "empty body";
        }

    } catch (Exception e) {
        result = e.getMessage();
    } finally {
        if (inBuffer != null) {
            try {
                inBuffer.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return result;
}

From source file:adapter.sos.BasicSensorObservationServiceClient.java

public void postXml(String strXML, String serviceURL) throws SOSException {

    HttpPost httppost = new HttpPost(serviceURL);
    HttpEntity entity = null;//from w  w  w . ja  v  a  2 s. com
    HttpResponse response = null;
    try {
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);

        nameValuePairs.add(new BasicNameValuePair("request", strXML));

        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        response = httpclient.execute(httppost);

        entity = response.getEntity();

        int code = response.getStatusLine().getStatusCode();

        if (code != 200) {
            throw new SOSException("Server replied with http error code: " + code);
        }

        examineReponse(entity);
    } catch (IOException e) {
        try {
            EntityUtils.consume(entity);
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        throw new SOSException("Cannot execute post: " + e.getCause());
    }
}

From source file:com.nuance.expertassistant.HTTPConnection.java

public static String sendPost(String postURL, HashMap<String, String> paramMap) throws Exception {

    String url = postURL;/* w  w  w .  ja v a2s. c  om*/

    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost(url);

    post.setHeader("User-Agent", USER_AGENT);

    if (paramMap != null) {
        List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
        System.out.println(" Printing Parameters ");
        for (String key : paramMap.keySet()) {
            System.out.println(key + " :: " + paramMap.get(key));

            urlParameters.add(new BasicNameValuePair(key, paramMap.get(key)));

        }

        post.setEntity(new UrlEncodedFormEntity(urlParameters));
    }
    HttpResponse response = client.execute(post);
    System.out.println("\nSending 'POST' request to URL : " + url);
    System.out.println("Post parameters : " + post.getEntity());
    System.out.println("Response Code : " + response.getStatusLine().getStatusCode());

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

    StringBuilder builder = new StringBuilder();
    for (String line = null; (line = rd.readLine()) != null;) {
        builder.append(line).append("\n");
    }
    /*
     System.out.print("JSON TEXT : " + builder.toString());
             
     String jsonText = builder.toString();
             
         jsonText = "{\"response\":" + jsonText + "}";
            
                     
             JSONObject object = new JSONObject(jsonText); */

    System.out.println(" The response code is :" + response.getStatusLine().getStatusCode());

    System.out.println(" The string returned is :" + builder.toString());

    return builder.toString();

}

From source file:ar.edu.ubp.das.src.chat.actions.SalasJoinAction.java

@Override
public ForwardConfig execute(ActionMapping mapping, DynaActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws SQLException, RuntimeException {
    try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {

        //get user data from session storage
        Gson gson = new Gson();
        Type usuarioType = new TypeToken<LoginTempBean>() {
        }.getType();/*from ww w . j  a  v a 2 s  . c o m*/
        String sessUser = String.valueOf(request.getSession().getAttribute("user"));
        LoginTempBean user = gson.fromJson(sessUser, usuarioType);

        //prepare http post
        HttpPost httpPost = new HttpPost("http://25.136.78.82:8080/usuarios-salas/");
        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("id_usuario", user.getId()));
        params.add(new BasicNameValuePair("id_sala", form.getItem("id_sala")));
        httpPost.setEntity(new UrlEncodedFormEntity(params));
        httpPost.addHeader("Authorization", "BEARER " + request.getSession().getAttribute("token"));
        httpPost.addHeader("accept", "application/json");

        CloseableHttpResponse postResponse = httpClient.execute(httpPost);

        HttpEntity responseEntity = postResponse.getEntity();
        StatusLine responseStatus = postResponse.getStatusLine();
        String restResp = EntityUtils.toString(responseEntity);

        if (responseStatus.getStatusCode() != 200) {
            throw new RuntimeException(restResp);
        }

        //get user data from session storage
        String salas = String.valueOf(request.getSession().getAttribute("salas"));
        List<SalaBean> salaList = gson.fromJson(salas, new TypeToken<List<SalaBean>>() {
        }.getType());
        SalaBean actual = salaList.stream().filter(s -> s.getId() == Integer.parseInt(form.getItem("id_sala")))
                .collect(Collectors.toList()).get(0);

        request.getSession().setAttribute("sala", actual);
        request.getSession().setAttribute("ultima_actualizacion", String.valueOf(System.currentTimeMillis()));

        return mapping.getForwardByName("success");

    } catch (IOException | RuntimeException e) {
        request.setAttribute("message", "Error al intentar ingresar a Sala: " + e.getMessage());
        response.setStatus(400);
        return mapping.getForwardByName("failure");
    }
}