Java HTTP Post executePost(String url, JSONObject data)

Here you can find the source of executePost(String url, JSONObject data)

Description

execute Post

License

Open Source License

Declaration

public static String executePost(String url, JSONObject data) throws IOException 

Method Source Code


//package com.java2s;
import org.json.JSONObject;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

public class Main {
    public static String executePost(String url, JSONObject data) throws IOException {
        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();

        //add reuqest header
        con.setRequestMethod("POST");
        con.setRequestProperty("User-Agent", "Mozilla/5.0");
        con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
        con.setRequestProperty("Content-Type", "application/json");

        // Send post request
        con.setDoOutput(true);/* ww  w . j av a2  s  .  c om*/
        DataOutputStream wr = new DataOutputStream(con.getOutputStream()); //TODO: Handle connection refused
        wr.writeBytes(data.toString());
        wr.flush();
        wr.close();

        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuilder response = new StringBuilder();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        return response.toString();
    }
}

Related

  1. doHttpPost(URL url, String requestBody)
  2. doPOST(HttpURLConnection conn, InputStream input)
  3. doPost(String targetURL, String urlParameters, String contentType)
  4. doPost(String theURL, Map nameValuePairs)
  5. doPost(URL url, String body, String... args)
  6. executePostWithCredentials(String targetURL, String urlParameters, String userName, String password)
  7. getHttpPOSTConnection(String urlStr, String charSet, Map props, Map params)
  8. httpGet(final String httpurl, final Map... requestProperties)
  9. httpPost(final String httpurl, final String data, final Map... requestProperties)