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
现在这是我得到的输出,我应该存储在一个字节数组中,将其发送回服务器请求页面?我仍然无法转发此请求):
答案 0 :(得分:0)
您需要打开另一个套接字到目标目标(根据firefox的请求)并在那里发送请求。保持连接到firefox的套接字打开,因为当你从目标目标获得响应时,你将从目标读取它并将其写回firefox。根据firefox中的管道设置,连接可能会关闭或者可能会发出更多请求。