我正嘗試使用Java創建一個簡單的Web代理應用程序(不使用HTTPUrlConnection類)。使用Java套接字類連接到Web服務器
到目前爲止,我已經成功地讓我的服務器在端口10000上偵聽,然後當我在瀏覽器中輸入URL時接受客戶端連接。
我現在需要我的代理將HTTP請求從瀏覽器轉發到實際的Web服務器(我輸入瀏覽器的URL)。
但是,我得到一個java.net.UnknownHostException:當試圖創建我的代理和Web服務器之間的套接字連接。有誰知道什麼可能導致這個問題?
以下是顯示錯誤和完整代碼的輸出。很感謝任何形式的幫助!
Starting the socket server at port:10000
Listening.....
Socket[addr=/127.0.0.1,port=64099,localport=10000]has connected
URL IS http://www.hotmail.com
Can't connect
java.net.UnknownHostException: http://www.hotmail.com
import java.net.*;
import java.io.*;
public class Proxy {
private ServerSocket serverSocket;
private int port;
public Proxy(int port) {
this.port = port; }
public static void main(String[] args) {
int port = 10000;
try {
// initialize the proxy
Proxy proxy = new Proxy(port);
proxy.start();
}
catch (IOException e) {
e.printStackTrace();
}
}
public void start() throws IOException {
System.out.println("Starting the socket server at port:" + port);
serverSocket = new ServerSocket(port);
//Listen for client connection
System.out.println("Listening.....");
Socket client = serverSocket.accept();
//A client has connected to this server
verifyClient(client);
}
private void verifyClient(Socket client) throws IOException {
System.out.println(client + "has connected");
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
//Parse the HTTP request from the browser and find the URL
String request;
while ((request = in.readLine()) != null) {
if (request.contains("http://")){
StringBuilder sb = new StringBuilder(request);
sb.delete(0,4);
sb.delete(sb.length()-9,sb.length());
makeConnection(sb.toString());
break;}
in.close();
}
}
private void makeConnection(String url) throws IOException{
//Establish connection between proxy & web server on socket
try {
InetAddress addr;
URL aURL = new URL(url);
System.out.println("URL IS " + aURL.toString());
Socket server = new Socket(urlString,80);
addr = server.getInetAddress();
System.out.println("IP is: " + addr);
System.out.println("Connected to " + addr);
server.close();
}
catch (IOException e) {
System.out.println("Can't connect");
System.out.println(e);
}
}
如果我輸入這個URL到我的瀏覽器中,我會看到一個頁面,上面寫着「找不到頁面」 – ControlAltDel 2014-09-29 16:53:20
啊,這是我的錯,我粘貼輸出時,我從問題頁面重新調整。上述錯誤發生在我嘗試的任何網站上。我已經更新了這個問題以避免混淆。 – user3792362 2014-09-29 16:57:09
如果您需要將套接字連接到www.stackoverload.com,如果之後包含路徑,則會出現錯誤 – ControlAltDel 2014-09-29 16:57:35