Java URL Post post(JSONObject json, String url)

Here you can find the source of post(JSONObject json, String url)

Description

POST mechanism

License

Open Source License

Parameter

Parameter Description
json a parameter
url a parameter

Return

success message

Declaration

public static String post(JSONObject json, String url) 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import org.json.JSONObject;

public class Main {
    private final static String CHARSET = "UTF-8";

    /**//from  w  w  w.ja v  a 2 s.c o  m
     * POST mechanism
     * @param json
     * @param url
     * @return success message
     */
    public static String post(JSONObject json, String url) {
        String query = json.toString();

        URLConnection connection;
        try {
            connection = new URL(url).openConnection();
            connection.setDoOutput(true); // Triggers POST.
            connection.setRequestProperty("Accept-Charset", CHARSET);
            connection.setRequestProperty("Content-Type", "application/json;charset=" + CHARSET);

            try (OutputStream output = connection.getOutputStream()) {
                output.write(query.getBytes(CHARSET));
            }

            InputStream response = connection.getInputStream();

            BufferedReader streamReader = new BufferedReader(new InputStreamReader(response, CHARSET));
            StringBuilder responseStrBuilder = new StringBuilder();

            String inputStr;
            while ((inputStr = streamReader.readLine()) != null) {
                responseStrBuilder.append(inputStr);
            }
            return responseStrBuilder.toString();
        } catch (MalformedURLException e) {
            System.out.println("Invalid URL");
        } catch (IOException e) {
            System.out.println("Invalid IO");
        }
        return "";
    }
}

Related

  1. post(String url, Map parameters)
  2. post(String url, String content)
  3. post(String url, String content)
  4. post(String urlstr, String[] params)