webクライアント

以下のプログラムはtestStringという文字をサーバーにPOSTし、サーバーが返してきた文字列を表示します。ブラウザが行っていることをプログラムで実行しています。
先ず、これをそのままコンパイルして動作を確認しなさい。

webクライアントを作る
import java.net.*;
import java.io.*;
/*
testStringという文字をPOSTし、サーバーから同じ文字を含めて返すテストプログラム
*/

class tiniwebClient
{
	static String host="localhost";
	Socket s=null;
	BufferedReader in=null;
	PrintStream out = null;	
	public static void main(String[] args)
	{
		new tiniwebClient(host).getAllInfo();
	}
	
	public tiniwebClient(String host)
	{
		this.host=host;
	}
	
	public void setHost(String host)
	{
		this.host=host;
	}
	
	public String getAllInfo()
	{
		String val;
		String ans=null;
	
		try {
			s = new Socket( host , 80 );
			in = new BufferedReader(new InputStreamReader(s.getInputStream()));
			out = new PrintStream(s.getOutputStream());
			String str= "read=command&text=testString&submit=exec"; 
			sendPostRequest(str);
			ans = readPacket();
		} catch (Exception e){
			System.err.println("Exception(getAllInfo)  : "+e);
		}
		int v = ans.indexOf("</FORM>")+7;
		int end = ans.indexOf("</body>", v);
		System.out.println(ans.substring(v, end));
		return ans;
	}
	
	public void sendPostRequest(String str)
	{
		try {
			int n = str.length();
			out.println("POST /tiniServer HTTP/1.0");
			out.println("Accept: */*");
			out.println("Content-Type: application/x-www-form-urlencoded");
			out.println("Content-Length: "+n);
			out.println();
			out.println(str);
		} catch (Exception e){
			System.err.println("Exception(sendPostRequest)  : "+e);
		} 
	}
	public String readPacket()
	{
		String val;
		String ans=null;
		String str;
		try {
			int n= "Content-length:".length();
			int m;
			int count=0;
			while((str = in.readLine()) != null){
				if((m=str.indexOf("Content-length:")) != -1) {	// あったら
					val = str.substring(m+n+1, str.length());
					in.readLine();
					if((str = in.readLine())!=null) {
						ans = str;
					}
				}
				else ans += str;
			}

		} catch (Exception e){
			System.err.println("Exception(readPacket)  : "+e);
		}
		return ans;
	}

}