gpt4 book ai didi

java - 基本 java net 客户端返回 400

转载 作者:行者123 更新时间:2023-12-02 10:33:54 24 4
gpt4 key购买 nike

以下代码已为 Horstmann 的《Big Java Early Objects》第 6 版 - 第 23.3 章复制。唯一的修改是包,由 eclipse 添加。

代码:

package zipCodeScrapper;
import java.io.InputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

public class client {
public static void main(String[] args) throws IOException {
// Get command-line arguments
String host;
String resource;

if (args.length == 2) {
host = args[0];
resource = args[1];
} else {
System.out.println("Getting / from horstmann.com");
host = "horstmann.com";
resource = "/";
}

// Open socket
final int HTTP_PORT = 80;
try (Socket s = new Socket(host, HTTP_PORT)) {

// Get streams
InputStream instream = s.getInputStream();
OutputStream outstream = s.getOutputStream();

// Turn streams into scanners and writers
Scanner in = new Scanner(instream);
PrintWriter out = new PrintWriter(outstream);

// Send command
String command = "GET " + resource + " HTTP/1.1\n" + "Host: " + host + "\n\n";
out.print(command);
out.flush();

while (in.hasNextLine()) {
String input = in.nextLine();
System.out.println(input);
}
}
}
}

代码收到 400 错误请求。我尝试将主机和资源替换为其他值,但仍然收到错误 400。

最佳答案

首先,阅读本文档。 RFC p1RFC2 p2

HTTP 的行分隔符不是 \n 。它必须是 \r\n 。欲了解更多信息,请阅读此主题;

What is line breaker in HTTP?

关于java - 基本 java net 客户端返回 400,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53441974/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com