使用 Java 套接字的 GET 请求

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32086560/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 19:38:15  来源:igfitidea点击:

GET request with Java sockets

javasocketshttpget

提问by user3236794

I am writing a simple program to send a get request to a specific url "http://badunetworks.com/about/". The request works if I send it to "http://badunetworks.com" but I need to send it to the about page.

我正在编写一个简单的程序来向特定的 URL“ http://badunetworks.com/about/”发送获取请求。如果我将其发送到“ http://badunetworks.com”,则该请求有效,但我需要将其发送到关于页面。

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();

    }

}

采纳答案by RAJKUMAR NAGARETHINAM

if the about page link is about.html ,then you have change this line wtr.println("GET / HTTP/1.1")into wtr.println("GET /about.html HTTP/1.1").

如果 about 页面链接是 about.html ,那么您已将此行更改wtr.println("GET / HTTP/1.1")wtr.println("GET /about.html HTTP/1.1").

in socket creation remove the /about

在套接字创建中删除 /about

wtr.println("GET / HTTP/1.1");--->this line call the home page of the host you specified.

wtr.println("GET / HTTP/1.1");--->此行调用您指定的主机的主页。

回答by Gerald Mücke

When you're doing such a low-level access to a webserver, you should understand the 7 OSI layers. Socket is on layer 5 and HTTP on layer 7. That's also the reason, why java.net.Socketonly accepts host names or InetAddr and no URLs. To do it with sockets, you have to implement the HTTP protocol properly, that is

当您对网络服务器进行如此低级别的访问时,您应该了解7 个 OSI 层。Socket 在第 5 层,HTTP 在第 7 层。这也是为什么java.net.Socket只接受主机名或 InetAddr 而没有 URL 的原因。要使用套接字来做到这一点,您必须正确实现 HTTP 协议,即

  • Create a socket connection to the hostand port, i.e. www.badunetworks.comand 80
  • Send a HTTP packet to the outputstream containing, method, resource by pathand protocol version, i.e. GET /about/ HTTP/1.1
  • Read and interpret the response properly (headers and body)
  • 创建一个套接字连接到主机端口,即www.badunetworks.com80
  • 通过路径和协议版本向输出流发送一个包含方法、资源的HTTP数据包,即GET /about/ HTTP/1.1
  • 正确阅读和解释响应(标题和正文)

But I wonder why you're doing it this complicated, there are a lot of alternatives to implementing low-level http clients yourself:

但我想知道你为什么要这样做这么复杂,有很多替代方案可以自己实现低级 http 客户端:

  • good old java.net.URL, as deprecated as its handling is, it's still one of the easiest way to read a resource, just call openStream()to read it
  • Apache HTTP Clientis one of the most widely used http client implementation for java, which is quite easy to use and more flexible than the reading via URL
  • javax.ws.rshas a good builder api for creating web clients
  • 旧的java.net.URL,尽管它的处理方式已被弃用,但它仍然是读取资源的最简单方法之一,只需调用openStream()即可读取它
  • Apache HTTP Client是java中使用最广泛的htt​​p客户端实现之一,使用起来相当方便,比通过URL读取更灵活
  • javax.ws.rs有一个很好的构建器 api 用于创建 Web 客户端

回答by Nightw0rk

you need open Socket to url without path e.g.

你需要打开 Socket to url 没有路径,例如

Socket("www.badunetworks.com", port);

and after send command GET /{path} HTTP/1.1 e.g.

在发送命令 GET /{path} HTTP/1.1 之后,例如

GET /about HTTP/1.1

... other header...

...其他标题...