Java HTTP Post sendJson(URL url, String method, String data)

Here you can find the source of sendJson(URL url, String method, String data)

Description

send Json

License

LGPL

Declaration

public static String sendJson(URL url, String method, String data) throws IOException 

Method Source Code


//package com.java2s;
//License from project: LGPL 

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;

public class Main {
    public static String sendJson(URL url, String method, String data) throws IOException {
        final StringBuffer buffer = new StringBuffer();

        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        //send json data
        connection.setRequestMethod(method);

        if (data != null) {
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setUseCaches(false);
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestProperty("Content-Length", String.valueOf(data.getBytes().length));

            OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
            writer.write(data);/*ww w  .  j a  va 2  s.c om*/
            writer.flush();
            writer.close();
        }

        //read response
        final BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));

        String line = reader.readLine();
        while (line != null) {
            buffer.append(line);
            line = reader.readLine();
        }

        reader.close();

        return buffer.toString();
    }
}

Related

  1. postURL(final URL url, final String request)
  2. put(String url, String content)
  3. put(URL host, String endpoint, String customer, String name, String version, InputStream in)
  4. putPOST(HttpURLConnection h, String query)
  5. requestPost(final String remoteUrl, final byte[] content)
  6. sendJsonData(final HttpURLConnection connection, final String data)
  7. sendPost(String link, String urlParameters)
  8. sendPost(String url, String data)
  9. sendPost(String url, String urlParameters)