Thursday, June 30, 2022

URLConnection : Writing Data to server

By using URLConnection, you can write data to a server. Once the connection is established, get the output stream of URLConnection object and write data to server.


public OutputStream getOutputStream() throws IOException
Returns an output stream that writes to this connection.

Note:
URLConnection don’t allow writing data to server by default, you have to call setDoOutput(true) to write data to server.

public void setDoOutput(boolean doOutput)
Set the DoOutput flag to true if you intend to use the URL connection for output, false if not. The default is false.

import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;

public class URLConnectionUtil {

  public static void writeDataToServer(String url, String data) {
    try {
      URL u = new URL(url);

      URLConnection urlConnection = u.openConnection();
      urlConnection.setDoOutput(true);
      
      OutputStream outputStream = urlConnection.getOutputStream();
      OutputStream buffered = new BufferedOutputStream(outputStream);
      OutputStreamWriter out = new OutputStreamWriter(buffered, "8859_1");
      
      out.write(data);
      
      out.flush();
      
      out.close();
    } catch (IOException ex) {
      System.err.println(ex);
    }
  }
}

No comments:

Post a Comment

Difference Between Socket and Server Socket in Java

Two essential Java classes-Socket and ServerSocket-have different functions when it comes to creating networked applications. These classes ...