Send httprequest in Java using java.net package
This is my code on the client side:
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 (Unknow开发者_JAVA百科nHostException 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();
}
}
and my http server:
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();
}
}
}
Request I am sending:
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
But my request is not coming in to HttpServerDemo.java's request handler.
Update
I am not able to debug my code since it's not hitting the request handler on the server and it works fine in a real browser. This is the response from the real browser when I open 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]
You forgot a blank newline between request headers and request body. The server now thinks that there are more headers to come and is waiting with handling the response. You must always insert a blank newline (CRLF) after the request headers. See also Wikipedia: HTTP.
Why use a Socket for HTTP at all? All this stuff is already solved for you with URL.openConnection().
精彩评论