[英]Send HTTPGET request over TCP connection to “localhost”
這是我的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();
}
}
}
}
當該程序運行時,如果我在Web瀏覽器上寫“ http:// localhost:8080 ”,則該程序可以處理Http get請求,並在Eclipse控制台上打印結果,但是我想通過使用Java代碼來實現。
實際上,首先,我想創建一個名稱為SimpleHTTPClient的類,並希望與SimpleHTTPServer類創建一個TCP套接字連接,並通過Java代碼將HTTPGET請求發送到我的本地主機。 我怎樣才能做到這一點? 實際上,我可以使用以下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套接字連接將HTTPGET請求發送到我的本地主機 。 我怎樣才能做到這一點?
為此,您必須打印請求的標題。 對於基本的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();
祝好運
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.