基本 java 网络客户端 returns 400
basic java net client returns 400
已为 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。
已为 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。