Java HTTP Post post(String rawUrl, String body)

Here you can find the source of post(String rawUrl, String body)

Description

post

License

Open Source License

Declaration

private static String post(String rawUrl, String body) 

Method Source Code

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

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URL;

import java.net.HttpURLConnection;

import java.util.UUID;

public class Main {
    private static String post(String rawUrl, String body) {
        BufferedReader reader = null;
        OutputStream out = null;/*from w w  w.  j a  v  a2  s . c om*/

        try {
            URL url = new URL(rawUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setRequestProperty("Content-Type", "application/json");
            out = connection.getOutputStream();
            out.write(body.getBytes());
            reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            StringBuffer result = new StringBuffer();
            String line;
            while ((line = reader.readLine()) != null)
                result.append(line);
            return result.toString();
        } catch (IOException ex) {
            ex.printStackTrace();
            return null;
        } finally {
            try {
                if (out != null)
                    out.close();
                if (reader != null)
                    reader.close();
            } catch (IOException ex) {
                ex.printStackTrace();
                return null;
            }
        }
    }

    private static String toString(UUID id) {
        return id.toString().replace("-", "");
    }
}

Related

  1. httpPost(String url, StringBuffer data)
  2. httpPost(String urlToRead, String post)
  3. httpPostText(String urlStr, String textString)
  4. post(String json, String url)
  5. post(String json, String url)
  6. post(String url, int timeout, Map header)
  7. post(String url, JsonNode body)
  8. post(String url, Map params, String charset)
  9. post(String url, String body, Map headers)