使用java套接字类连接到Web服务器

时间:2014-09-29 16:45:44

标签: java sockets http webserver

我正在尝试使用Java创建一个简单的Web代理应用程序(不使用HTTPUrlConnection类)。

到目前为止,我已成功让我的服务器侦听端口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);
    }

}

1 个答案:

答案 0 :(得分:0)

从您的更新中,您似乎正在尝试创建与" http://www.hotmail.com"的套接字连接。这应该是www.hotmail.com。 " http://"在此之前是一个问题。