HttpClient类是一个简单的HTTP客户端程序,它已GET方式向HTTP服务器发送HTTP请求
package com.http;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
public class HTTPClient {
public static void main(String[] args) {
String uri="index.htm";//请求HTTP的请求uri
if(args.length!=0)uri=args[0];
doGet("localhost",8080,uri); //按照GET请求方式访问HTTPServer
}
private static void doGet(String host, int port, String uri) {
// TODO Auto-generated method stub
Socket socket=null;
try{
socket=new Socket(host,port); //与HTTPserver建立TCP连接
StringBuffer sb=new StringBuffer("GET"+uri+" HTTP/1.1\r\n");//HTTP请求的一行
//发送HTTP请求
OutputStream socketOut=socket.getOutputStream();
socketOut.write(sb.toString().getBytes());
//接收服务器响应的结果
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}finally{
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
package com.http;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.security.Provider.Service;
public class HTTPServer {
public static void main(String[] args) {
int port;
ServerSocket serverSocket;
try{
port=Integer.parseInt(args[0]);
}catch (Exception e) {
// TODO: handle exception
System.out.println("port=8080(默认)");
port=8080;
}
try{
serverSocket=new ServerSocket(port);
System.out.println("服务器正在监听端口:"+serverSocket.getLocalPort());
while(true){
try{
final Socket socket=serverSocket.accept();
System.out.println("服务器正在建立一个新的tcp链接,该客户的地址为:" +
socket.getInetAddress()+":"+socket.getPort());
service(socket);
}catch (Exception e) {
// TODO: handle exception
}
}
}catch (Exception e) {
// TODO: handle exception
}
}
private static void service(Socket socket)throws Exception {
// TODO Auto-generated method stub
//读取Http请求信息
InputStream socketIn=socket.getInputStream();
Thread.sleep(500);
int size=socketIn.available();
byte[] buffer=new byte[size];
socketIn.read(buffer);
String request=new String(buffer);
System.out.println(request);
}
}