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

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

Introduction

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

Prototype

public HttpPost(final String uri) 

Source Link

Usage

From source file:com.niceapps.app.HttpClient.java

public static JSONObject SendHttpPost(String URL, JSONObject jsonObjSend) {

    try {/*from   ww  w . j a  va  2 s.  c o m*/
        DefaultHttpClient httpclient = new DefaultHttpClient();
        HttpPost httpPostRequest = new HttpPost(URL);

        StringEntity se;
        se = new StringEntity(jsonObjSend.toString());

        // Set HTTP parameters
        httpPostRequest.setEntity(se);
        httpPostRequest.setHeader("Accept", "application/json");
        httpPostRequest.setHeader("Content-Type", "application/json");

        HttpResponse response = (HttpResponse) httpclient.execute(httpPostRequest);

        if (response.getStatusLine().getStatusCode() == 200) {
            HttpEntity entity = response.getEntity();
            JSONObject jsonObjRecv = new JSONObject(EntityUtils.toString(entity));

            return jsonObjRecv;
        } else {
            return null;
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:org.energyos.espi.datacustodian.console.ImportUsagePoint.java

public static void upload(String filename, String url, HttpClient client) throws IOException {
    HttpPost post = new HttpPost(url);
    MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

    File file = new File(filename);
    entity.addPart("file", new FileBody(((File) file), "application/rss+xml"));

    post.setEntity(entity);/*from ww  w. j  a  v a2  s.  com*/

    client.execute(post);
}

From source file:net.saga.sync.gameserver.portal.CreatePlayer.java

public static Player createPlayer(HttpServletRequest req) throws UnsupportedEncodingException {
    SkeletonKeySession session = (SkeletonKeySession) req.getAttribute(SkeletonKeySession.class.getName());

    HttpClient client = new HttpClientBuilder().trustStore(session.getMetadata().getTruststore())
            .hostnameVerification(HttpClientBuilder.HostnameVerificationPolicy.ANY).build();
    try {//from  w  ww. ja  v  a 2s . c  o m
        HttpPost post = new HttpPost("https://localhost:8443/gameserver-database/player");
        post.addHeader("Authorization", "Bearer " + session.getTokenString());
        post.setEntity(new StringEntity("{}"));
        try {
            HttpResponse response = client.execute(post);
            if (response.getStatusLine().getStatusCode() != 200) {
                throw new RuntimeException("" + response.getStatusLine().getStatusCode());
            }
            HttpEntity entity = response.getEntity();
            InputStream is = entity.getContent();
            try {
                return JsonSerialization.readValue(is, Player.class);
            } finally {
                is.close();
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    } finally {
        client.getConnectionManager().shutdown();
    }
}

From source file:email.mandrill.SendMail.java

public static MessageResponses sendMail(Message message) {
    try {// www  .  j a  v  a  2s.  c o m
        logger.log(Level.INFO, "Message:" + message.toJSONString());

        HttpClient httpclient = HttpClients.createDefault();
        HttpPost httppost = new HttpPost("https://mandrillapp.com/api/1.0/messages/send.json");

        String request = message.toJSONString();
        HttpEntity entity = new ByteArrayEntity(request.getBytes("UTF-8"));
        httppost.setEntity(entity);
        //Execute and get the response.
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity responseEntity = response.getEntity();

        if (responseEntity != null) {
            InputStream instream = responseEntity.getContent();
            try {
                StringWriter writer = new StringWriter();
                IOUtils.copy(instream, writer, "UTF-8");
                String theString = writer.toString();

                MessageResponses messageResponses = new MessageResponses(theString);
                //Do whateveer is needed with the response.
                logger.log(Level.INFO, theString);
                return messageResponses;
            } finally {
                instream.close();
            }
        }
    } catch (Exception e) {
        logger.log(Level.SEVERE, util.Utility.logMessage(e, "Exception while updating org name:", null));
    }
    return null;
}

From source file:com.twitter.heron.integration_test.core.HttpUtils.java

static int httpJsonPost(String newHttpPostUrl, String jsonData) throws IOException, ParseException {
    HttpClient client = HttpClientBuilder.create().build();
    HttpPost post = new HttpPost(newHttpPostUrl);

    StringEntity requestEntity = new StringEntity(jsonData, ContentType.APPLICATION_JSON);

    post.setEntity(requestEntity);//  w  w  w.  ja  va 2  s  . c  o m
    HttpResponse response = client.execute(post);

    return response.getStatusLine().getStatusCode();
}

From source file:com.e2.MessageSender.java

public static void send(String text) {
    Map<String, String> json = new HashMap<String, String>();
    int second = Integer.parseInt(String.valueOf(System.currentTimeMillis()).substring(9, 10));
    try {//from  ww  w .  ja  v  a 2s.  co m
        String url = "http://taku.st-sweet.com:8082/e_000/hosts";

        HttpClient client = HttpClientBuilder.create().build();
        HttpPost httpPost = new HttpPost(url);

        //Create Message Object
        json.put("mmCall", "1");
        json.put("mType", "5");
        json.put("id", "tw_" + String.valueOf(System.currentTimeMillis()));
        json.put("x", "50");
        json.put("y", second % 2 == 0 ? "5" : "95");
        json.put("appearFade", "true");
        json.put("appearSlide", "2");
        json.put("appearSize", "1");

        json.put("disappearFade", "true");
        json.put("disappearSlide", "3");
        json.put("disappearSize", "2");

        json.put("liveTime", "150");

        json.put("rectColor", colorPattern[second / 2]);
        json.put("text", text);
        json.put("textColor", "#DDD");
        json.put("textAlign", "2");

        List<NameValuePair> nvps = new ArrayList<>();
        for (Iterator it = json.entrySet().iterator(); it.hasNext();) {
            Map.Entry entry = (Map.Entry<String, String>) it.next();
            nvps.add(new BasicNameValuePair(entry.getKey().toString(), entry.getValue().toString()));
        }
        //    System.out.println(new UrlEncodedFormEntity(nvps).toString());

        httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
        client.execute(httpPost);

    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:su.fmi.photoshareclient.remote.LoginHandler.java

public static boolean login(String username, char[] password) {
    try {//from  w ww.j ava 2 s. c om
        ProjectProperties properties = new ProjectProperties();
        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(
                "http://" + properties.get("socket") + properties.get("restEndpoint") + "/user/login");
        StringEntity input = new StringEntity(
                "{\"username\":\"" + username + "\",\"password\":\"" + new String(password) + "\"}",
                ContentType.create("application/json"));
        post.setHeader("Content-Type", "application/json");
        post.addHeader(BasicScheme.authenticate(new UsernamePasswordCredentials(username, new String(password)),
                "UTF-8", false));
        post.setEntity(input);

        if (username.isEmpty() || password.length == 0) {
            return false;
        }
        HttpResponse response = (HttpResponse) client.execute(post);
        if (response.getStatusLine().getStatusCode() == 200) {
            String authString = username + ":" + new String(password);
            byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
            authStringEncr = new String(authEncBytes);
            return true;
        } else {
            return false;
        }
    } catch (UnsupportedEncodingException ex) {
        Logger.getLogger(LoginGUI.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(LoginGUI.class.getName()).log(Level.SEVERE, null, ex);
    }
    return false;
}

From source file:org.hobbit.spatiotemporalbenchmark.transformations.value.AddressFromNominatim.java

public static String getAddress(double latitude, double longitude) {
    String strAddress = "";
    String point = latitude + "," + longitude;

    String url = "http://nominatim.openstreetmap.org/reverse?format=json&lat=" + latitude + "&lon=" + longitude
            + "&addressdetails=1&accept-language=en";

    HttpPost httppost = new HttpPost(url);
    HttpClient httpclient = new DefaultHttpClient();
    String result = "";
    try {/*from w w w .  ja  va 2 s. co m*/
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity resEntityGet = response.getEntity();
        if (resEntityGet != null) {
            result = EntityUtils.toString(resEntityGet);
        }
    } catch (Exception e) {
        System.out.println("Exception:" + e);
    }
    try {
        if (result != null) {
            JSONObject json = new JSONObject(result);
            strAddress = json.get("display_name").toString();
        }
    } catch (Exception e) {
    }
    try {
        if (!strAddress.equals("")) {
            pointAddressMap.put(point, strAddress);
            FileUtils.writeStringToFile(f, point + "=" + strAddress + "\n", true);
        }
    } catch (IOException ex) {
        Logger.getLogger(CoordinatesToAddress.class.getName()).log(Level.SEVERE, null, ex);
    }
    return strAddress;
}

From source file:io.kamax.mxisd.util.RestClientUtils.java

public static HttpPost post(String url, String body) {
    StringEntity entity = new StringEntity(body, StandardCharsets.UTF_8);
    entity.setContentType(ContentType.APPLICATION_JSON.toString());
    HttpPost req = new HttpPost(url);
    req.setEntity(entity);//from w w  w . ja v  a  2s . co  m
    return req;
}

From source file:org.hobbit.spatiotemporalbenchmark.transformations.value.AddressFromGoogleMapsApi.java

public static String getAddress(double latitude, double longitude) {
    String strAddress = "";
    String point = latitude + "," + longitude;
    String url = "https://maps.googleapis.com/maps/api/geocode/json?latlng=" + latitude + "," + longitude
            + "&sensor=true&language=en";

    HttpPost httppost = new HttpPost(url);
    HttpClient httpclient = new DefaultHttpClient();
    String result = "";
    try {/*from  ww  w .j  av  a  2  s .c om*/
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity resEntityGet = response.getEntity();
        if (resEntityGet != null) {
            result = EntityUtils.toString(resEntityGet);
        }
    } catch (Exception e) {
        System.out.println("Exception:" + e);
    }
    try {
        /*Keeps the first address form the results*/
        if (result != null) {
            JSONObject json = new JSONObject(result);
            JSONArray ja = json.getJSONArray("results");
            //System.out.println(result.toString());
            for (int i = 0; i < 1; i++) {
                strAddress = ja.getJSONObject(i).getString("formatted_address");
            }
        }
    } catch (Exception e) {
    }
    try {
        if (!strAddress.equals("")) {
            pointAddressMap.put(point, strAddress);
            FileUtils.writeStringToFile(f, point + "=" + strAddress + "\n", true);
        }
    } catch (IOException ex) {
        Logger.getLogger(CoordinatesToAddress.class.getName()).log(Level.SEVERE, null, ex);
    }
    return strAddress;
}