我正在編寫Web代理,到目前爲止,我可以從客戶端讀取GET請求,格式化並將其發送到服務器,我相信我已經能夠從服務器獲得響應,但我不確定如何將響應發送到客戶端。如何從服務器(作爲Web代理)讀取HTTP響應並向客戶端發送響應
Scanner readClient = new Scanner(new InputStreamReader(client.getInputStream()));
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(client.getInputStream()));
System.out.println("Client Request: ");
String request;
String host = "";
String path = "";
String[] parts = new String[4];
while((request = bufferedReader.readLine())!= null) {
if (request.indexOf("deflate") != -1) {
break;
}
if(request.indexOf("GET") != -1){
parts = request.split(" ");
path = parts[1];
System.out.println("THIS IS THE PATH: " + path);
}
if(request.indexOf("Host") != -1){
parts = request.split(": ");
host = parts[1];
System.out.println("THIS IS THE HOST: " + host);
}
System.out.println(request);
}
Socket server = new Socket(host, 80);
System.out.println("Successfully connected to host: " + host);
PrintWriter writeServer = new PrintWriter(new DataOutputStream(server.getOutputStream()));
InputStream readServer = server.getInputStream();
writeServer.print("GET " + path + "\r\n" + "Host: " + host + "\r\n" + "Connection: close\r\n\r\n");
writeServer.flush();
OutputStream writeClient = client.getOutputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte buffer[] = new byte[1024];
for(int s; (s=readServer.read(buffer)) != -1;)
{
baos.write(buffer, 0, s);
}
byte result[] = baos.toByteArray();
System.out.println("message sent");
}
catch (Exception e) {
System.out.println("Start Exception: " + e.getMessage());
}
}
**不知道我應該如何記錄的問題所做出的編輯,但我已經改變了我的措辭,並更新了我的代碼,以及包含更多。
你期望什麼樣的輸出?來自網頁的文字可能是正確的迴應。 –
玩弄wget,看看它是一個Web服務器正在返回並將其與您的程序正在做的事情進行比較。 – Duston
我想要HTTP響應。所以不是來自網頁的文字。收到響應後,我會將它發送給客戶端並加載網頁。我不希望終端中的文本,我只是打印它,以便我可以看到從服務器返回的內容。 – AndieM