发送HTTP请求

时间:2013-07-29 15:25:26

标签: java html sockets request serversocket

我正在写一个网络客户端。我有以下代码。

public class Connection extends Thread{
public final static int PORT = 1337;
private ServerSocket svrSocket = null;
private Socket con  =  null;
public Connection(){

    try{
        svrSocket = new ServerSocket(PORT);
        System.out.println("Conected to: " + PORT);

    }catch(IOException ex)
    {
       System.err.println(ex);
       System.out.println("Unable to attach to port");
   }

}

public void run(){

while(true)
{

        try{
            con = svrSocket.accept();//on this part the program stops
            System.out.println("Client request accepted");
            PrintWriter out = new PrintWriter(con.getOutputStream());
            BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
            out.println("GET /<index.html> HTTP/1.1");

            out.println("***CLOSE***");
            System.out.println(in.readLine());
           /*
            String s;

            while((s = in.readLine()) != null)
            {
                System.out.println(s);
            }*/
            out.flush();
            out.close();
            in.close();
            con.close();

            System.out.println("all closed");
    }
        catch(IOException ex)
    {
        ex.printStackTrace();

    }



}
}

}

后面将使用run方法。我有一个名为index.html的文件。此文件与java代码位于同一文件中。我要对请求做的是发送HTML文件。但是,如果我在网络浏览器localhost:1337上运行此程序,则会显示以下内容。

GET /<index.html> HTTP/1.1
***CLOSE***

这不应该显示。应显示index.html中HTML代码结果的页面。

Index.html代码:

<html>
 <head>
  <title>       </title>

 </head>
 <body bgcolor = "#ffffcc" text = "#000000">
  <h1>Hello</h1>
  <p>This is a simple web page</p>
 </body>
</html>

如何让这个html页面显示在浏览器中?

谢谢

2 个答案:

答案 0 :(得分:0)

你混淆了几件事。首先:你所写的是服务器,而不是客户。

第二:你没有遵循HTT协议。

GET /<index.html> HTTP/1.1(错误,应为GET /index.html HTTP/1.1)是客户端发送的请求(如Web浏览器)。相反,它是你的服务器发送它。

快速解决方案:

请先阅读GET文件的内容并将其打印到{{1},而不是发送此静态文本(包含***CLOSE***的行和包含index.html的行)流。

编辑:以下是http数据流的快速概述:

  1. 客户端(例如浏览器)连接到服务器
  2. 客户端发送请求,如

    GET /theFileIWant.html HTTP/1.1\r\n
    Host: localhost\r\n
    \r\n
    
  3. 此时,客户端通常会停止发送任何内容并等待服务器响应。这被称为“请求/响应”模型。

  4. 服务器读取请求数据并找出它必须执行的操作。
  5. 输出(在这种情况下:文件的内容)发送到客户端,前面是HTTP响应头。​​
  6. 连接可以保持打开或关闭,具体取决于客户端请求和服务器响应的HTTP头。

答案 1 :(得分:0)

似乎你的代码一切都很好,似乎你需要从输入流中读取HTTP头,这样你就可以获得所请求的文件名,然后使用Socket输出流从文件中写出响应。 / p>
OutputStream output = con.getOutputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String fileName = readHeader(in);
String baseDir = System.getProperty("my.base.dir", "/home/myname/httpserver");
boolean exist = true;
InputStream fileIn = null;
try {
   File requestedFile = new File(baseDir, fileName);
   fileIn = new FileInputStream(requestedFile);
} catch(Exception e){
    exist = false;
}

String server = "Java Http Server";
String statusLine = null;
String typeLine = null;
String body = null;
String lengthLine = "error";

if (exist) {
   statusLine = "HTTP/1.0 200 OK" + "\r\n";
   //get content type by extension
   typeLine = "Content-type: html/text  \r\n";
   lengthLine = "Content-Length: " + (new Integer(fileIn.available())).toString() + "\r\n";
} else {
  statusLine = "HTTP/1.0 404 Not Found" + CRLF;
  typeLine = "text/html";
  body = "<HTML>" + "<HEAD><TITLE>404</TITLE></HEAD>" + "<BODY>404 Not Found"+"</BODY></HTML>";
}

output.write(statusLine.getBytes());
output.write(server.getBytes());
output.write(typeLine.getBytes());
output.write(lengthLine.getBytes());

output.write("\r\n".getBytes());

if (exist) {
   byte[] buffer = new byte[1024];
   int bytes = 0;

   while ((bytes = fileIn.read(buffer)) != -1) {
     output.write(buffer, 0, bytes);
   }
} else {
   output.write(body.getBytes());
}
//close sreams