HTTP协议传输代码


本人是初学者,对很多深入的问题不太清楚,各位前辈帮我写个简单,很简单的THHP协议传输数据代码,不是从WEB页面传的,是要从JAVA客户端传的,要客户端和服务器代码,先谢谢了

https http协议

好人卡还我 11 years, 6 months ago

这可以是一道很有趣的面试题.
我写一个很笨的http服务器, 又多笨? 它根本不知道client和它说什么, 只会自言自语.

   
  import java.io.PrintWriter;
  
import java.net.ServerSocket;
import java.net.Socket;

public class TestHttpServer {
private static ServerSocket serverSocket;
private static String stupid="Yes, I am stupid. So what?";
private static String output="HTTP/1.1 200 OK\n"+
"Content-Type: text/html; charset=UTF-8\n" +
"Content-Length: "+stupid.length()+
"\n\n"+stupid;
public static void main(String argv[]) {
try {
serverSocket = new ServerSocket(4444);
Socket clientSocket = null;
while(null != (clientSocket = serverSocket.accept())){
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
out.println(output);
Thread.sleep(1000);
out.close();
clientSocket.close();
}
} catch (Exception e) {
System.out.println("server error.");
System.exit(-1);
}
}
}

接着我们在浏览器输入 http://localhost:4444/whatever
返回: Yes, I am stupid. So what?

Client代码:

   
  import java.io.BufferedReader;
  
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class TestHttpClient {
public static void main(String[] args) throws IOException {

Socket socket = null;
PrintWriter out = null;
BufferedReader in = null;

try {
socket = new Socket("localhost", 4444);
out = new PrintWriter(socket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out.println("GET http://localhost:4444/ HTTP/1.1");
String line=null;
while(null != (line=in.readLine())){
System.out.println(line);
}
out.close();
in.close();
socket.close();
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
}

可以对上面的HTTP server做改进:
1. 处理client的给出的URL;
2. 对client的不同的http方法(GET, POST..)做处理;
3. 处理各种http request header;(encoding, cookie,)
4. 处理http response header;
5. 处理各种HTTP response code;

木哈哈哈,恩 answered 11 years, 6 months ago

Your Answer