这是我的java http服务器程序:
package alan;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
public class SimpleHTTPServer {
public static void main(String args[] ) throws IOException {
ServerSocket server = new ServerSocket(8080);
System.out.println("Listening for connection on port 8080 ....");
while (true) {
Socket clientSocket = server.accept();
InputStreamReader isr = new InputStreamReader(clientSocket.getInputStream());
BufferedReader reader = new BufferedReader(isr);
String line = reader.readLine();
while (!line.isEmpty()) {
System.out.println(line);
line = reader.readLine();
}
}
}
}
当这个程序正在运行时,如果我写" http://localhost:8080"在Web浏览器上,程序可以处理Http get请求,并在Eclipse控制台上输出结果,但我想通过使用java代码来完成。
实际上,首先,我想创建一个名为SimpleHTTPClient的类,我想创建一个与SimpleHTTPServer类的TCP Socket连接,并通过java代码将HTTPGET请求发送到我的localhost。我怎样才能做到这一点?实际上,我可以发送带有URL连接的HTTPGET请求,如下所示:
package alan;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.net.URL;
import java.net.URLConnection;
import java.net.UnknownHostException;
public class SimpleHTTPClient {
static Socket socket = null;
public static void main(String args[]) throws UnknownHostException, IOException {
URL oracle = new URL("http://localhost:8080");
URLConnection yc = oracle.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
}
}
但我想通过TCP套接字连接向我的 localhost 发送HTTPGET请求。我怎么能这样做?
答案 0 :(得分:1)
为此,您必须打印请求标题。 对于基本HTTP请求,只需在标头中添加http方法和主机。
见下面的代码
Socket s = new Socket(InetAddress.getByName("stackoverflow.com"), 80);
PrintWriter pw = new PrintWriter(s.getOutputStream());
pw.println("GET / HTTP/1.1");
pw.println("Host: stackoverflow.com");
pw.println("");
pw.flush();
BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
String t;
while ((t = br.readLine()) != null) {
System.out.println(t);
}
br.close();
祝你好运