带有Java套接字的HTTP客户端

时间:2018-10-07 15:55:21

标签: java sockets http client

我尝试用Java打开TCP套接字,并将GET请求发送到服务器(www.abc.net.au),然后将响应打印到控制台。

客户代码:

import java.util.Scanner;

import java.net.InetAddress;
import java.net.SocketAddress;
import java.net.InetSocketAddress;
import java.net.Socket;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;

public class Client {
    public static void main(String[] args) throws Exception{

        Scanner sc;
        String addressString;
        int port =80;
        int timeoutMs = 30000;
        String temp;

        //Read address from commandline
        sc =new Scanner(System.in);
        System.out.print("Adresse: ");
        addressString = sc.next();
        sc.close();
        //Open socket
        InetAddress addr = InetAddress.getByName(addressString);
        SocketAddress sockaddr = new InetSocketAddress(addr, port);
        Socket socket = new Socket();

        //Connection timeout
        socket.connect(sockaddr,timeoutMs);

        System.out.println( socket.getPort() +"\n");

        //Define input/output
        BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        PrintWriter pw = new PrintWriter(socket.getOutputStream(), true);

        //Send GET request
        pw.print("GET / HTTP/1.1\r\n");
        pw.print("Host: "+ addressString +"\r\n\r\n");
        while((temp=br.readLine())!=null){
            System.out.println(temp);

        }
        //Close Input/Output and Socket
        pw.close();
        br.close();
        socket.close();
    }
}

代码似乎一直有效,直到到达一段时间,然后我得到:

HTTP/1.0 408 Request Time-out
Server: AkamaiGHost
Mime-Version: 1.0
Date: Sun, 07 Oct 2018 15:36:40 GMT
Content-Type: text/html
Content-Length: 218
Expires: Sun, 07 Oct 2018 15:36:40 GMT

<HTML><HEAD>
<TITLE>Request Timeout</TITLE>
</HEAD><BODY>
<H1>Request Timeout</H1>
The server timed out while waiting for the browser's request.<P>
Reference&#32;&#35;2&#46;3d5b6068&#46;1538926600&#46;0
</BODY></HTML>

Process finished with exit code 0

我不明白是什么原因导致的,已经在寻找关于stackoverflow,java2s和我在家读书的答案。尝试其他页面通常仅以以下内容结束:

Process finished with exit code 0

没别的。

知道我的请求中缺少什么/不正确吗?

应用所有提示。

1 个答案:

答案 0 :(得分:0)

PrintWriter具有用于存储数据的内部缓冲区,因此,在调用print时-没有任何内容发送到服务器

来自https://docs.oracle.com/javase/7/docs/api/java/io/PrintWriter.html

  

与PrintStream类不同,如果启用了自动刷新,则仅在 println printf format 方法之一时才执行被调用,而不是每当换行符输出时。

因此,您可以使用以下方法代替print或显式调用flush

pw.print("GET / HTTP/1.1\r\n");
pw.print("Host: " + addressString + "\r\n\r\n");
pw.flush(); // actually send data to server