Java HTTP Post post(URL url, String content)

Here you can find the source of post(URL url, String content)

Description

post

License

Open Source License

Declaration

public static String post(URL url, String content) throws IOException 

Method Source Code

//package com.java2s;
/*//  w w  w.  j  ava  2  s .c  om
 * Copyright ? 2014 - 2016 | Wurst-Imperium | All rights reserved.
 * 
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

import java.io.BufferedReader;
import java.io.DataOutputStream;

import java.io.IOException;
import java.io.InputStreamReader;

import java.net.HttpURLConnection;
import java.net.Proxy;

import java.net.URL;

public class Main {
    public static String post(URL url, String content) throws IOException {
        return post(url, content, "application/x-www-form-urlencoded");
    }

    public static String post(URL url, String content, String contentType) throws IOException {

        HttpURLConnection connection = (HttpURLConnection) url.openConnection(Proxy.NO_PROXY);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", contentType);
        connection.setRequestProperty("Content-Length", "" + content.getBytes().length);
        connection.setRequestProperty("Content-Language", "en-US");
        connection.setUseCaches(false);
        connection.setDoInput(true);
        connection.setDoOutput(true);
        DataOutputStream output = new DataOutputStream(connection.getOutputStream());
        output.writeBytes(content);
        output.flush();
        output.close();

        BufferedReader input = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        StringBuffer buffer = new StringBuffer();
        for (String line; (line = input.readLine()) != null;) {
            buffer.append(line);
            buffer.append("\n");
        }
        input.close();
        return buffer.toString();
    }
}

Related

  1. post(String url, String body, Map headers)
  2. post(String url, String payload)
  3. post(String url, String postdata, String cookie)
  4. Post(URL url, Map fields)
  5. post(URL url, Map values)
  6. post(URL url, String contentType, byte[] data)
  7. postCall(JsonObject json, String url)
  8. postData(Reader data, URL endpoint, Writer output)
  9. postForm(String url, Map params)