Send HTTP Post request [Java]

Questions about programming languages and debugging
Post Reply
User avatar
maboroshi
Dr. Mab
Dr. Mab
Posts: 1624
Joined: 28 Aug 2005, 16:00
18

Send HTTP Post request [Java]

Post by maboroshi »

How can I send an HTTP Post request by Java

I looked at a few examples but they really made no sense ;)

*cheers

Maboroshi

User avatar
bad_brain
Site Owner
Site Owner
Posts: 11636
Joined: 06 Apr 2005, 16:00
19
Location: In your eye floaters.
Contact:

Post by bad_brain »


User avatar
ayu
Staff
Staff
Posts: 8109
Joined: 27 Aug 2005, 16:00
18
Contact:

Post by ayu »

It's just like any other socket connection using Java, then it's simply to follow the http protocol =)

I wrote you a small example here, it sends a request to google and prints the result.

Code: Select all

import java.net.*;
import java.io.*;

public class httpReq
{
	public static void main(String[] args)
	{
			String receive = "";

			try {
				Socket clientSocket	= new Socket("google.com", 80);
				PrintWriter out		= new PrintWriter(clientSocket.getOutputStream(), true);
				BufferedReader in	= new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
				
				out.println("GET /index.html HTTP/1.1");
				out.println("Host: google.com");
				out.println("Connection: Close");
				out.println();


				while((receive = in.readLine()) != null)
				{
					System.out.println(receive);
				}

				out.close();
				in.close();
			} catch(UnknownHostException e) {
				System.err.print("Couldn't establish a connection\n");
				System.exit(1);
			}
			catch(IOException e) {
				System.err.print("You have encountered an I/O error, drop down and give me 20\n");
				System.exit(1);
			}

		
		}
}
EDIT: I wrote it fast, so tell me if you want comments and I might be able to add that later tonight.
"The best place to hide a tree, is in a forest"

Post Reply