0

I have to implement a post request in plain Java.

I have read the following question:

How to make a post request to a json RESTful Service from Java?

this is a part of the example

String url = "https://myStore.com/REST-API/";
String requestBody = "{\"searchProduct\": \"" + searchProduct + "\"}";

URL obj = new URL(url);

HttpsURLConnection connection = (HttpsURLConnection) obj
        .openConnection();

connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");

OutputStream outputStream = connection.getOutputStream();

outputStream.write(requestBody.getBytes());

My question is: why the parameters are written on the output stream? As far as I know, output stream is for collecting the output of a request, not to make it.

So just a curiosity, consider that I am obviously not skilled on this.

Lore
  • 1,286
  • 1
  • 22
  • 57

2 Answers2

1

The goal of InputStream and OutputStream is to abstract streams. By stream, I mean the way of the processed data (Input of the program or Output)
If the application receives information from the stream, use the InputStream. If it sends data then OutputStream

  • InputStreamused to read data from a source.
    var input = new FileInputStream("input.txt");// Read the data
  • OutputStreamused for writing data to a destination.
    var output = new FileOutputStream("output.txt");// Write the data

You should read answers in the related question : There are more explanations.

Vinetos
  • 150
  • 1
  • 7
1

First let explain how HttpConnectionURL works.

When you want to request data from a server,

  1. you first create a connection to that server.
  2. Then you write data to the connection (request)
  3. and finally read data from the connection (response).

So to write data to the connection you get a reference to the Connection's OutputStream and write data to it.

OutputStreamWriter writer = new OutputStreamWriter(
            connection.getOutputStream());
    writer.write("message=" + message);

To read data from the connection you get a reference to the Connection's InputStream and read data from it.

InputStreamReader reader = new InputStreamReader(connection.getInputStream());
reader.read();

Generally you use OutputStream when data is flowing out of your program (to file,network etc.,) and InputStream when data is flowing into your program (from file,network etc.,).

I think this will give you the clarity you are looking for.

This answer explains in detail how HttpConnectionURL works

Hari Mani
  • 76
  • 2