使用java.net包在Java中发送httprequest

时间:2010-09-23 22:17:16

标签: java http

这是我在客户端的代码:

import java.io.*;
import java.net.*;

public class httpClient {

    public void TcpSocket()
    {
        String sentence;
        String modifiedSentence;
        StringBuffer contents= null;

        //open a socket connection on port 80
        try{
            Socket clientSocket = new Socket("localhost", 8080);

            //send message to the server
            DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());

            //read message from the server
            BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));

            //read http request message from a file
            File file = new File("/home/x/Desktop/test.txt");
            contents = new StringBuffer();     
            BufferedReader reader = null;
            reader = new BufferedReader(new FileReader(file));
            String text = null;

            // repeat until all lines is read
            while ((text = reader.readLine()) != null)
            {
                contents.append(text).append(System.getProperty("line.separator"));
            } 
            //end reading file

            //Send message
            sentence = contents.toString();
            outToServer.writeBytes(sentence + '\n');
            modifiedSentence = inFromServer.readLine();
            System.out.println("FROM SERVER: " + modifiedSentence);

            clientSocket.close();
        }
        catch (UnknownHostException e) {
            System.err.println("Don't know about host");
            System.exit(1);
        } catch (IOException e) {
            System.err.println("Couldn't get I/O for the connection");
            System.exit(1);
        }

    }

    public static void main(String args[])
    {
        httpClient cl = new httpClient();
        cl.TcpSocket();
    }
}

和我的http服务器:

import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.concurrent.Executors;

import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;

public class HttpServerDemo {
  public static void main(String[] args) throws IOException {
    InetSocketAddress addr = new InetSocketAddress(8080);
    HttpServer server = HttpServer.create(addr, 0);

    server.createContext("/", new MyHandler());
    server.setExecutor(Executors.newCachedThreadPool());
    server.start();
    System.out.println("Server is listening on port 8080" );
  }
}

class MyHandler implements HttpHandler {
  public void handle(HttpExchange exchange) throws IOException {
    System.out.println("I am in Server request Handler"); <---------------Request is not coming here
    String requestMethod = exchange.getRequestMethod();
    if (requestMethod.equalsIgnoreCase("GET")) {
      Headers responseHeaders = exchange.getResponseHeaders();
      responseHeaders.set("Content-Type", "text/plain");
      exchange.sendResponseHeaders(200, 0);

      OutputStream responseBody = exchange.getResponseBody();
      Headers requestHeaders = exchange.getRequestHeaders();
      Set<String> keySet = requestHeaders.keySet();
      Iterator<String> iter = keySet.iterator();
      while (iter.hasNext()) {
        String key = iter.next();
        List values = requestHeaders.get(key);
        String s = key + " = " + values.toString() + "\n";
        responseBody.write(s.getBytes());
      }
      responseBody.close();
    }
  }
}

请求我发送:

GET /index.html HTTP/1.1
Host: localhost
User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.3) Gecko/20091020 Ubuntu/9.10 (karmic) Firefox/3.5.3
Accept: /
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
Connection: keep-alive

但是我的请求没有进入HttpServerDemo.java的请求处理程序。

更新

我无法调试我的代码,因为没有在服务器上访问请求处理程序,并且它在真实浏览器中正常工作。当我打开http://localhost:8080

时,这是真实浏览器的响应
Host = [localhost:8080]
Accept-charset = [ISO-8859-1,utf-8;q=0.7,*;q=0.7]
Accept-encoding = [gzip,deflate]
Connection = [keep-alive]
Keep-alive = [300]
Accept-language = [en-us,en;q=0.5]
User-agent = [Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.3) Gecko/20091020 Ubuntu/9.10 (karmic) Firefox/3.5.3]

Accept = [text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8]

2 个答案:

答案 0 :(得分:0)

您忘记了请求标头和请求正文之间的空白换行符。服务器现在认为有更多的头文件正在等待处理响应。您必须始终在请求标头后插入空白换行符(CRLF)。另请参阅Wikipedia: HTTP

答案 1 :(得分:0)

为什么要使用Socket for HTTP?所有这些东西都已经通过URL.openConnection()解决了。