A URL Reader/Writer Class That Writes/Reads Data to/from a URL - Java Network

Java examples for Network:URL

Description

A URL Reader/Writer Class That Writes/Reads Data to/from a URL

Demo Code

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.net.URL;
import java.net.URLConnection;
import java.util.Map;

public class Main {
  public static String getURLContent(String urlStr, String input) {
    BufferedReader br = null;//from  www. j a va2  s . c om
    BufferedWriter bw = null;

    try {
      URL url = new URL(urlStr);
      URLConnection connection = url.openConnection();

      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));

      StringBuffer sb = new StringBuffer();
      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();
        }
      }
    }
    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.java2s.com/";
    String content = getURLContent(urlStr, "");
    System.out.println(content);
  }
}

Result


Related Tutorials