我在我的学校接受了这个培训任务:在“SimpleClient”中进行更改,以便它对命令行上给出的地址发出GET请求,并将响应内容存储到磁盘上的文件中。 / p>
import java.net.*;
import java.io.*;
public class SimpleClient {
public static void main(String[] args) {
try {
Socket con = new Socket(args[0], Integer.parseInt(args[1]));
PrintStream out = new PrintStream(con.getOutputStream());
out.print(args[2]);
out.write(0); // mark end of message
out.flush();
InputStreamReader in = new InputStreamReader(con.getInputStream());
int c;
while ((c = in.read())!=-1)
System.out.print((char)c);
con.close();
} catch (IOException e) {
System.err.println(e);
}
}
}
据我所知,Socket的“con”实例应通过端口号(args [1])与主机(args [0],例如www.google.com)建立连接。然后创建一个PrintStream“out”,但是out.print(args [2])和out.write(0)的功能是什么?我完全不理解这个程序,所以如果有人可以向我解释并告诉我应该改变什么以使其工作,我将不胜感激。
答案 0 :(得分:0)
打开套接字连接与触发GET请求不同。看看Using java.net.URLConnection to fire and handle HTTP requests
答案 1 :(得分:0)
好的,如果有人对此感兴趣,我找到了解决方案。
import java.net.*;
import java.io.*;
public class SimpleClient {
public static void main(String[] args) {
try {
FileWriter fw = new FileWriter(args[args.length - 1]);
BufferedWriter bw = new BufferedWriter(fw);
try {
Socket con = new Socket(args[0], Integer.parseInt(args[1]));
PrintStream out = new PrintStream(con.getOutputStream());
out.println("GET /search?q=" + args[2] + " HTTP/1.1");
out.println("Host: www.google.com");
out.println("");
out.write(0); // mark end of message
out.flush();
InputStreamReader in = new InputStreamReader(
con.getInputStream());
int c;
while ((c = in.read()) != -1)
bw.write((char) c);
con.close();
} catch (IOException e) {
System.err.println(e);
}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}