final int portNumber = 8128;
String str;
int start = 0;
int endSg = 0;
int endCom = 0;
String ReqWeb=null;
System.out.println("Creating server socket on port " + portNumber);
ServerSocket serverSocket = new ServerSocket(portNumber);
BufferedReader inFromServer;
OutputStream out;
PrintWriter outw;
Socket forwardSocket = null;
while (true)
{
Socket socket = serverSocket.accept(); //get client request
String from = socket.getInetAddress().toString();
System.out.println("Accepted connection from " + from);
OutputStream os = socket.getOutputStream();
PrintWriter pw = new PrintWriter(os, true);
pw.println("What's your request?");
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
//System.out.println(str);
while((str = br.readLine())!=null){
System.out.println(str);
if(str!=null){
start = str.indexOf("Host: ") + 6;
endSg = str.indexOf(".sg", start) + 3;
endCom = str.indexOf(".com", start) + 4;
if(((endSg>3)||(endCom>4))&&(start>4)){
if(endSg>3)
ReqWeb = str.substring(start, endSg);
else if(endCom>3)
ReqWeb = str.substring(start, endCom);
}
}
}
System.out.println(ReqWeb);
if(ReqWeb!=null){
//ReqWeb = str.substring(start);
System.out.println(ReqWeb);
forwardSocket = new Socket(ReqWeb, 80);
}
pw.println(str);
pw.println(ReqWeb);
//socket.close();
if(forwardSocket!=null){
inFromServer = new BufferedReader(new InputStreamReader(forwardSocket.getInputStream()));
out = forwardSocket.getOutputStream();
outw = new PrintWriter(out, false);
outw.print(str);
}
}
输出 :
Creating server socket on port 8128
Accepted connection from /127.0.0.1
null
Accepted connection from /127.0.0.1
GET (http://)stackoverflow.com/questions/12900825/how-do-i-forward-the-http-request-back-to-the-browser-proxy-java HTTP/1.0
Host: stackoverflow.com
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:15.0) Gecko/20100101 Firefox/15.0.1
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip, deflate
Connection: close
Proxy-Connection: close
Pragma: no-cache
现在这是我得到的输出,我应该存储在字节数组中以将其发送回服务器以请求页面吗?我仍然无法转发此请求):