URLConnection Post

In this chapter you will learn:

  1. How to post to URLConnection

Post to URLConnection

The following code posts values to a URL with URLConnection. It creates a URL first and open connection to that URL. Then it calls the set the output to true using setDoOutput. After that it posts to the URL by writing to the OutputStreamWriter.

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
// j  a v a2s  .  co  m
public class Main {

  public static void main(String[] args) throws Exception {
    URL url = new URL("http://www.java2s.com");
    URLConnection conn = url.openConnection();
    conn.setDoOutput(true);
    OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());

    writer.write("value=1&anotherValue=1");
    writer.flush();
    String line;
    BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    while ((line = reader.readLine()) != null) {
      System.out.println(line);
    }
    writer.close();
    reader.close();

  }
}

Next chapter...

What you will learn in the next chapter:

  1. Get the cookie value from URL
  2. Sending a Cookie to an HTTP Server
Home » Java Tutorial » URL URI
URL
URL Creation
URL for jar file
URL Components
Convert file path to URL
URL Relative
URL Protocol
Read from URL
Compare URL
URLConnection
HTTP Header
URLConnection Post
Cookie
URLConnection Read
HttpURLConnection
HttpURLConnection Properties
HttpURLConnection proxy
HttpURLConnection Authenticator
HTTPS
JarURLConnection
Encode a URL
Decode a URL
URI
URI Normalization
URI Resolution
URI Relativization
Convert URI to URL
IP Address
IP Ping
NetworkInterface