HTTP client

In this chapter you will learn:

  1. A simple HTTP client

A simple HTTP client

The following code uses Socket creates a HTTP client. We can create a HTTP client with URLConnection or HttpURLConnection. This time we are using more low level api to create the HTTP client. From the code below we can see that we have to send an HTTP request to the web server.

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
//from   j  a v a 2 s .  co m
public class Main {
  public static void main(String[] args) throws Exception {
    InetAddress addr = InetAddress.getByName("www.google.com");
    Socket socket = new Socket(addr, 80);
    boolean autoflush = true;
    PrintWriter out = new PrintWriter(socket.getOutputStream(), autoflush);
    BufferedReader in = new BufferedReader(

    new InputStreamReader(socket.getInputStream()));
    // send an HTTP request to the web server
    out.println("GET / HTTP/1.1");
    out.println("Host: www.google.com:80");
    out.println("Connection: Close");
    out.println();

    // read the response
    boolean loop = true;
    StringBuilder sb = new StringBuilder(8096);
    while (loop) {
      if (in.ready()) {
        int i = 0;
        while (i != -1) {
          i = in.read();
          sb.append((char) i);
        }
        loop = false;
      }
    }
    System.out.println(sb.toString());
    socket.close();
  }
}

The code above generates the following result.

Next chapter...

What you will learn in the next chapter:

  1. A Thin SMTP Client
Home » Java Tutorial » Socket

Socket

    Socket
    Socket creation
    Socket read
    HTTP client
    SMTP Client
    Cipher Socket
    Socket connection and thread

ServerSocket

    ServerSocket
    ServerSocket connection
    File server and client
    Thread based Server
    Time server
    SocketServer based zip server
    ServerSocketChannel
    Channel selector

SocketChannel

    SocketChannel Creation
    Read and write with SocketChannel
    SocketChannel based HTTP client
    SocketChannel Asynchronous

ServerSocketChannel

    ServerSocketChannel
    Channel selector

SSL

    SSL Client Socket
    SSL Server Socket

UDP

    DatagramSocket
    DatagramChannel
    Multicast Group

Cookie

    Cookies