http最常用的两种请求方法,get和post,现在用socket模仿post请求,以便能更深入理解http协议,代码如下:
package com.ppt.socket;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.URL;
public class SocketHttpPost {
private final String END = "\r\n";
private Socket client;
private InputStream is;
private OutputStream os;
private String host;
private String path;
public SocketHttpPost(String url) {
try {
init(url);
} catch(Exception e) {
e.printStackTrace();
}
}
private void init(String url) throws Exception {
URL temp = new URL(url);
this.host = temp.getHost();
this.path = temp.getPath();
int port = temp.getPort();
client = new Socket();
SocketAddress address = new InetSocketAddress(this.host, port);
client.connect(address, 5000);
client.setSoTimeout(10000);
is = client.getInputStream();
os = client.getOutputStream();
}
private void post() throws IOException {
String data = "username=ppt&password=ppt";
StringBuffer sb = new StringBuffer();
sb.append("POST "+ this.path +" HTTP/1.1" + END);
sb.append("Host: " + this.host + END);
sb.append("User-Agent:Mozilla/4.0(compatible;MSIE6.0;Windows NT 5.0)" + END);
sb.append("Accept-Language:zh-cn" + END);
sb.append("Accept-Encoding:deflate" + END);
sb.append("Accept:*/*" + END);
sb.append("Connection:Keep-Alive" + END);
sb.append("Content-Type: application/x-www-form-urlencoded" + END);
sb.append("Content-Length: "+ data.length() + END);
sb.append(END);
sb.append(data);
String requestString = sb.toString();
System.out.println(requestString);
os.write(requestString.getBytes());
os.flush();
byte[] rBuf = new byte[1024];
int i = is.read(rBuf);
System.out.println(new String(rBuf));
}
public static void main(String[] args) throws IOException {
String url = "http://localhost:9090/pptinterface/hello";
SocketHttpPost post = new SocketHttpPost(url);
post.post();
}
}