Example usage for org.apache.http.client.methods HttpPost setEntity

List of usage examples for org.apache.http.client.methods HttpPost setEntity

Introduction

In this page you can find the example usage for org.apache.http.client.methods HttpPost setEntity.

Prototype

public void setEntity(final HttpEntity entity) 

Source Link

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);/*from w  w w.  j  a va 2s  . co m*/
    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:middleware.HTTPRequest.java

public static void doPostVuelo(String jsonRequest) throws UnsupportedEncodingException, IOException {
    String url = "http://localhost:8084/MVIv2/webapi/vuelos";
    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpPost postRequest = new HttpPost(url);
    StringEntity input = new StringEntity(jsonRequest);
    input.setContentType("application/json");
    postRequest.setEntity(input);

    HttpResponse response = httpClient.execute(postRequest);

    if (response.getStatusLine().getStatusCode() != 200) {
        throw new RuntimeException("ERROR AL INSERTAR DEL TIPO: " + response.getStatusLine().getStatusCode());
    }//from   w  w w.j  a v  a 2s  .c  o m

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

    String output;
    System.out.println("Output from Server .... \n");
    while ((output = br.readLine()) != null) {
        System.out.println(output);
    }

    httpClient.getConnectionManager().shutdown();

}

From source file:middleware.HTTPRequest.java

public static void doPostReserva(String jsonRequest) throws UnsupportedEncodingException, IOException {
    String url = "http://localhost:8084/MVIv2/webapi/reservas";
    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpPost postRequest = new HttpPost(url);
    StringEntity input = new StringEntity(jsonRequest);
    input.setContentType("application/json");
    postRequest.setEntity(input);

    HttpResponse response = httpClient.execute(postRequest);

    if (response.getStatusLine().getStatusCode() != 200) {
        throw new RuntimeException("ERROR AL INSERTAR DEL TIPO: " + response.getStatusLine().getStatusCode());
    }/*from www.  j  ava2s  .c  o m*/

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

    String output;
    System.out.println("Output from Server .... \n");
    while ((output = br.readLine()) != null) {
        System.out.println(output);
    }

    httpClient.getConnectionManager().shutdown();

}

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

public static long getExistingRecord(String title, int category_id) {

    List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
    urlParameters.add(new BasicNameValuePair("title", title));
    urlParameters.add(new BasicNameValuePair("category_id", Long.valueOf(category_id).toString()));

    HttpResponse result;//from  www.j a v a 2s .  c  o m
    String resultStr;
    LibraryCollection libraryCollection = new LibraryCollection();

    try {
        System.out.println("invoking getExistingRecord, Title: " + title + ", Category ID: " + category_id);
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost post = new HttpPost(Constants.SELECT_LAST_ADDED_LIBRARY_RESOURCE);
        post.setEntity(new UrlEncodedFormEntity(urlParameters));
        result = httpClient.execute(post);
        System.out.println(Constants.RESPONSE_STATUS_CODE + result);
        resultStr = Util.getStringFromInputStream(result);

        libraryCollection = Marshal.unmarshal(LibraryCollection.class, resultStr);

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

    }

    if (null != libraryCollection.getLibrary()) {
        return libraryCollection.getLibrary()[0].getContent_id();
    }
    return -1;
}

From source file:com.sugarcrm.candybean.webservices.WS.java

/**
 * Send a DELETE, GET, POST, or PUT http request
 *
 * @param op          The type of http request
 * @param uri         The http endpoint/*w w w . ja  va2 s . com*/
 * @param headers     Map of header key value pairs
 * @param body        String representation of the request body
 * @param contentType The content type of the body
 * @return Key Value pairs of the response
 * @throws CandybeanException When http request failed
 */
public static Map<String, Object> request(OP op, String uri, Map<String, String> headers, String body,
        ContentType contentType) throws CandybeanException {
    switch (op) {
    case DELETE:
        return handleRequest(new HttpDelete(uri), headers);
    case GET:
        return handleRequest(new HttpGet(uri), headers);
    case POST:
        HttpPost post = new HttpPost(uri);
        if (body != null) {
            post.setEntity(new StringEntity(body, contentType));
        }
        return handleRequest(post, headers);
    case PUT:
        HttpPut put = new HttpPut(uri);
        if (body != null) {
            put.setEntity(new StringEntity(body, contentType));
        }
        return handleRequest(put, headers);
    default:
        /*
         * JLS 13.4.26: Adding or reordering constants in an enum type will not break compatibility with
         * pre-existing binaries.
         * Thus we include a default in the case that a future version of the enum has a case which is not
         * one of the above
         */
        throw new CandybeanException("Unrecognized OP type... Perhaps your binaries are the wrong version?");
    }
}

From source file:cardgametrackercs319.DBConnectionManager.java

public static String getPlayerInfo(String playerID) throws UnsupportedEncodingException, IOException {
    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost("http://ozymaxx.net/cs319/player_info.php");

    post.setHeader("User-Agent", USER_AGENT);
    ArrayList<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
    urlParameters.add(new BasicNameValuePair("pid", playerID));

    post.setEntity(new UrlEncodedFormEntity(urlParameters));

    HttpResponse response = client.execute(post);
    BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
    StringBuffer result = new StringBuffer();
    String resLine = "";

    while ((resLine = reader.readLine()) != null) {
        result.append(resLine);/* w w w . java  2  s. co  m*/
    }

    return result.toString();
}

From source file:com.jeecms.common.web.ClientCustomSSL.java

public static String getInSsl(String url, File pkcFile, String storeId, String params, String contentType)
        throws Exception {
    String text = "";
    // ???PKCS12/* w  w  w  .j ava 2  s .com*/
    KeyStore keyStore = KeyStore.getInstance("PKCS12");
    // ?PKCS12?
    FileInputStream instream = new FileInputStream(pkcFile);
    try {
        // PKCS12?(ID)
        keyStore.load(instream, storeId.toCharArray());
    } finally {
        instream.close();
    }

    // Trust own CA and all self-signed certs
    SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, storeId.toCharArray()).build();
    // Allow TLSv1 protocol only
    // TLS 
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" },
            null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
    // httpclientSSLSocketFactory
    CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
    try {
        HttpPost post = new HttpPost(url);
        StringEntity s = new StringEntity(params, "utf-8");
        if (StringUtils.isBlank(contentType)) {
            s.setContentType("application/xml");
        }
        s.setContentType(contentType);
        post.setEntity(s);
        HttpResponse res = httpclient.execute(post);
        HttpEntity entity = res.getEntity();
        text = EntityUtils.toString(entity, "utf-8");
    } finally {
        httpclient.close();
    }
    return text;
}

From source file:core.HttpClient.java

/**
 * Checks if we have the latest version/*from  ww  w.  ja va2 s .co m*/
 * 
 * @param version
 * @return boolean - true if version is not up to date
 */
public static boolean isUpdateRequired(String version) {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    try {
        HttpResponse response;
        HttpEntity entity;

        HttpPost httpost = new HttpPost(COMPANY_WEBSITE);
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("version", version));
        httpost.setEntity(new UrlEncodedFormEntity(nvps));
        response = httpclient.execute(httpost);

        entity = response.getEntity();
        String data = "", line;
        BufferedReader br = new BufferedReader(new InputStreamReader(entity.getContent()));
        while ((line = br.readLine()) != null) {
            data += line;
        }

        if (data.startsWith("true")) {
            return true;
        } else {
            return false;
        }
    } catch (ClientProtocolException e) {
        e.printStackTrace();
        return false;
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    } finally {
        httpclient.getConnectionManager().shutdown();
    }
}

From source file:de.bytefish.fcmjava.client.utils.HttpUtils.java

private static <TRequestMessage, TResponseMessage> TResponseMessage internalPost(
        HttpClientBuilder httpClientBuilder, IFcmClientSettings settings, TRequestMessage requestMessage,
        Class<TResponseMessage> responseType) throws Exception {

    try (CloseableHttpClient client = httpClientBuilder.build()) {

        // Initialize a new post Request:
        HttpPost httpPost = new HttpPost(settings.getFcmUrl());

        // Get the JSON representation of the given request message:
        String requestJson = JsonUtils.getAsJsonString(requestMessage);

        // Set the JSON String as data:
        httpPost.setEntity(new StringEntity(requestJson));

        // Execute the Request:
        try (CloseableHttpResponse response = client.execute(httpPost)) {

            // Get the HttpEntity of the Response:
            HttpEntity entity = response.getEntity();

            // If we don't have a HttpEntity, we won't be able to convert it:
            if (entity == null) {
                // Simply return null (no response) in this case:
                return null;
            }//w w  w  .ja  v a 2 s  . co m

            // Get the JSON Body:
            String responseBody = EntityUtils.toString(entity);

            // Make Sure it is fully consumed:
            EntityUtils.consume(entity);

            // And finally return the Response Message:
            return JsonUtils.getEntityFromString(responseBody, responseType);
        }
    }
}

From source file:org.neo4j.nlp.examples.sentiment.main.java

private static String executePost(String targetURL, String payload) {
    try {//from  w w  w.  j  a  v a2  s. co  m

        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost postRequest = new HttpPost(targetURL);

        StringEntity input = new StringEntity(payload);
        input.setContentType("application/json");
        postRequest.setEntity(input);

        HttpResponse response = httpClient.execute(postRequest);

        if (response.getStatusLine().getStatusCode() != 200) {
            throw new RuntimeException(
                    "Failed : HTTP error code : " + response.getStatusLine().getStatusCode());
        }

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

        StringBuilder output = new StringBuilder();
        while (br.read() != -1) {
            output.append(br.readLine()).append('\n');
        }

        httpClient.getConnectionManager().shutdown();

        return "{" + output.toString();

    } catch (IOException e) {

        e.printStackTrace();

    }

    return null;
}