Search code examples
javainputstreamhttpurlconnectionoutputstream

How to upload InputStream to HttpURLConnection


I have created a HttpURLConnection using which i need to upload a file to a specific URL. Below is my code

String uURL = "http:some_domain/add";
URL url = new URL(uURL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "text/plain");
connection.setRequestMethod("PUT");

OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());

InputStream iStream = getContent("ABC", "test.json");   

Now, i have retrieved my content in iStream and want to upload it using OutputStreamWriter. How can i upload the content?


Solution

  • If your content is text file you can use OutputStreamWriter. (It's look like your file is a json)

    try (OutputStream os = con.getOutputStream();
        OutputStreamWriter osw = new OutputStreamWriter(os, "UTF-8")) {
        String data = "{\"name\": \"John\", \"age\": 30}";
        osw.write(data);
        osw.flush();
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    

    If your content is binary file you can use DataOutputStream

    try (OutputStream os = con.getOutputStream();
        DataOutputStream dos = new DataOutputStream(os)) {
        byte[] data = {0x01, 0x02, 0x03, 0x04, 0x05};
        dos.write(data);
        dos.flush();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }