Java URL post

Description

Java URL post

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Map;

public class Main {
  public static String getURLContent(String urlStr, String input) {
    BufferedReader br = null;/*w w  w.j  a va 2s .  com*/
    BufferedWriter bw = null;

    try {
      URL url = new URL(urlStr);

      URLConnection connection = url.openConnection();
      // call setDoOutput(true) to indicate that you will write
      // to the connection. By default, it is false.
      connection.setDoOutput(true);

      connection.connect();

      OutputStream ous = connection.getOutputStream();
      bw = new BufferedWriter(new OutputStreamWriter(ous));
      bw.write(input);
      bw.flush();
      bw.close();

      printRequestHeaders(connection);

      InputStream ins = connection.getInputStream();

      br = new BufferedReader(new InputStreamReader(ins));

      StringBuilder sb = new StringBuilder();
      String msg = null;
      while ((msg = br.readLine()) != null) {
        sb.append(msg);
        sb.append("\n"); // Append a new line
      }
      return sb.toString();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      if (br != null) {
        try {
          br.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }

    // If we arrive here it means there was an error
    return null;
  }

  public static void printRequestHeaders(URLConnection connection) {
    Map headers = connection.getHeaderFields();
    System.out.println("Request Headers are:");
    System.out.println(headers);
    System.out.println();
  }

  public static void main(String[] args) {
    String urlStr = "http://www.httpbin.org/post";

    try {

      String content = getURLContent(urlStr, "asdf");

      System.out.println("Returned data from the server is:");
      System.out.println(content);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}



PreviousNext

Related