使用Java套接字获取GET请求
我正在编写一个简单的程序来向特定url“ 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客户端:
- 很好的旧java.net.URL ,因为它的处理已被弃用,它仍然是读取资源的最简单方法之一,只需调用
openStream()
来读取它 - Apache HTTP Client是java中使用最广泛的http客户端实现之一,它比使用URL读取更容易使用且更灵活
- javax.ws.rs有一个很好的构建器api用于创建Web客户端