[英]GET request with Java sockets
我正在編寫一個簡單的程序來向特定網址“ http://badunetworks.com/about/ ”發送獲取請求。 如果我將其發送到“ http://badunetworks.com ”,請求仍然有效,但我需要將其發送到about頁面。
package badunetworks;
import java.io.*;
import java.net.*;
public class GetRequest {
public static void main(String[] args) throws Exception {
GetRequest getReq = new GetRequest();
//Runs SendReq passing in the url and port from the command line
getReq.SendReq("www.badunetworks.com/about/", 80);
}
public void SendReq(String url, int port) throws Exception {
//Instantiate a new socket
Socket s = new Socket("www.badunetworks.com/about/", port);
//Instantiates a new PrintWriter passing in the sockets output stream
PrintWriter wtr = new PrintWriter(s.getOutputStream());
//Prints the request string to the output stream
wtr.println("GET / HTTP/1.1");
wtr.println("Host: www.badunetworks.com");
wtr.println("");
wtr.flush();
//Creates a BufferedReader that contains the server response
BufferedReader bufRead = new BufferedReader(new InputStreamReader(s.getInputStream()));
String outStr;
//Prints each line of the response
while((outStr = bufRead.readLine()) != null){
System.out.println(outStr);
}
//Closes out buffer and writer
bufRead.close();
wtr.close();
}
}
如果about頁面鏈接是about.html,那么你已將此行wtr.println("GET / HTTP/1.1")
wtr.println("GET /about.html HTTP/1.1").
為wtr.println("GET /about.html HTTP/1.1").
在套接字創建中刪除/ about
wtr.println("GET / HTTP/1.1");
--->此行調用您指定的主機的主頁。
你需要打開Socket到url沒有路徑,例如
Socket("www.badunetworks.com", port);
並在發送命令GET / {path} HTTP / 1.1之后
GET /about HTTP/1.1
......其他標題......
當您對Web服務器進行如此低級別的訪問時,您應該了解7個OSI層 。 Socket在第5層,第7層是HTTP。這也是為什么java.net.Socket只接受主機名或InetAddr而沒有URL的原因。 要使用套接字,您必須正確實現HTTP協議,即
www.badunetworks.com
和80
GET /about/ HTTP/1.1
將HTTP數據包發送到包含方法,資源的輸出流 但我想知道為什么你這么復雜,有很多替代方法可以自己實現低級別的http客戶端:
openStream()
來讀取它
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.