HTTP GET Request 是用 Packetyzer 偷看 Firefox 的 GET 而來的
這個小程式純粹教學用途, 所以很陽春
// shinder.lin@gmail.com
// www.riarock.com
import java.net.*;
import java.io.*;
import java.util.*;
import java.nio.charset.*;
public class SD_HTTPTest
{
public static void main(String arg[])
{
String uri = "shinder.idv.tw";
try
{
if(arg.length >= 1){
uri = arg[0];
}
Socket mySocket = new Socket(uri, 80);
if(mySocket.isConnected())
{
OutputStream out = mySocket.getOutputStream();
BufferedWriter bWriter = new BufferedWriter(
new OutputStreamWriter(out));
String msg = "GET / HTTP/1.1\r\n"+
"Host: "+uri+"\r\n"+
"User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-TW; rv:1.7.12) Gecko/20050919 Firefox/1.0.7\r\n"+
"Accept: application/x-shockwave-flash,text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5\r\n"+
"Accept-Language: zh-tw,en-us;q=0.7,en;q=0.3\r\n"+
"Accept-Encoding: gzip,deflate\r\n"+
"Accept-Charset: Big5,utf-8;q=0.7,*;q=0.7\r\n"+
"Keep-Alive: 300\r\n"+
"Connection: keep-alive\r\n\r\n";
bWriter.write(msg);
bWriter.flush();
}else{
System.out.println("Not Connected");
}
if(mySocket.isConnected())
{
InputStream in = mySocket.getInputStream();
BufferedReader bReader = new BufferedReader(
new InputStreamReader(in));
char cbuf[] = new char[4096];
//去除多餘的字元
bReader.read(cbuf);
int count = 0;
for(count=0; count < cbuf.length; count++){
if(cbuf[count] == 0){
break;
}
}
String msg = new String(cbuf, 0, count);
System.out.println(msg);
}
}
catch(IOException ex){
System.out.println("連結錯誤!");
}
catch(Exception ex){
System.out.println("發生例外:"+ex.toString());
}
}
}
沒有留言:
張貼留言