我基于套接字编写网络服务器。所以我可以获得HTTP请求标头:
import java.net.ServerSocket;
import java.net.Socket;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;
public class HttpServer {
public static void main(String[] args) throws Throwable {
//http://localhost:3000
ServerSocket ss = new ServerSocket(3000);
while (true) {
//Waiting for socket
Socket s = ss.accept();
System.out.println("Client accepted");
//The main process
new SocketProcessor(s,ss).start();
}
}
private static class SocketProcessor implements Runnable {
private Thread t;
private Socket s;
private InputStream is;
private OutputStream os;
private SocketProcessor(Socket s,ServerSocket ss) throws Throwable {
t = new Thread(this, "Server Thread");
this.s = s;
this.is = s.getInputStream();
this.os = s.getOutputStream();
}
public void run() {
try {
readInputHeaders();
writeResponse("<html><body><h1>Hello</h1></body></html>");
} catch (Throwable t) {
/*do nothing*/
} finally {
try {
s.close();
} catch (Throwable t) {
}
}
System.out.println("Client processing finished");
}
public void start()
{
t.start();
}
private void writeResponse(String s) throws Throwable {
String response = "HTTP/1.1 200 OK\r\n" +
"Server: Server\r\n" +
"Content-Type: text/html\r\n" +
"Content-Length: " + s.length() + "\r\n" +
"Connection: close\r\n\r\n";
String result = response + s;
os.write(result.getBytes());
os.flush();
}
private void readInputHeaders() throws Throwable {
BufferedReader br = new BufferedReader(new InputStreamReader(is));
while(true) {
String s = br.readLine();
System.out.println(s);
if(s == null || s.trim().length() == 0) {
break;
}
}
}
}
}
输入:
http://localhost:3000/?page=1
输出:
GET /?page=1 HTTP/1.1
Host: localhost:3000
Connection: keep-alive
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.154 Safari/537.36
Accept-Encoding: gzip,deflate,sdch
Accept-Language: ru-RU,ru;q=0.8,en-US;q=0.6,en;q=0.4,bg;q=0.2
但现在我需要获取查询字符串参数:
page=1
我知道GET-request不是最好的例子,因为我可以从URI获得params,但这不适用于POST。 那么如何从socket获取查询字符串参数?我不知道尝试。
答案 0 :(得分:0)
当然我找到了解决方案。 POST参数在新行之后着陆。因此检查行是否为空无济于事。我们可以通过char检查Content-Length和读取请求char。