Java HTTP Post post(URL url, String contentType, byte[] data)

Here you can find the source of post(URL url, String contentType, byte[] data)

Description

Sends HTTP POST request

License

Open Source License

Parameter

Parameter Description
url the URL to connect to
contentType the data's content type
data the data to send to the server

Exception

Parameter Description
IOException an exception
ProtocolException an exception

Return

Streamed response from server

Declaration

public static InputStream post(URL url, String contentType, byte[] data) throws IOException, ProtocolException 

Method Source Code


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

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.URL;

public class Main {
    /**/*  www.java  2s.  c o m*/
     * Sends HTTP POST request
     * @param url the URL to connect to
     * @param contentType the data's content type
     * @param data the data to send to the server
     * @return Streamed response from server
     * @throws IOException
     * @throws ProtocolException
     */
    public static InputStream post(URL url, String contentType, byte[] data) throws IOException, ProtocolException {

        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        con.setDoOutput(true);
        con.setRequestMethod("POST");
        con.setRequestProperty("content-Type", contentType);

        OutputStream out = con.getOutputStream();
        try {
            out.write(data, 0, data.length);
            out.flush();
        } finally {
            out.close();
        }
        return con.getInputStream();
    }
}

Related

  1. post(String url, String payload)
  2. post(String url, String postdata, String cookie)
  3. Post(URL url, Map fields)
  4. post(URL url, Map values)
  5. post(URL url, String content)
  6. postCall(JsonObject json, String url)
  7. postData(Reader data, URL endpoint, Writer output)
  8. postForm(String url, Map params)
  9. postHTTPQuery(String url, String urlParameters)