资源简介
东北大学实验,网络实践。实验二代码,http实现
东北大学实验,网络实践。实验二代码,http实现
代码片段和文件信息
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Scanner;
public class Client {
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
//链接服务器
//发送请求头
while(true){
Socket s=new Socket(“localhost“8888);
PrintStream writer = new PrintStream(s.getOutputStream());
System.out.println(“请输入下载文件“);
String filename = new Scanner(System.in).nextLine();
writer.println(“GET /“+filename+“ HTTP/1.1“);
writer.println(“Host:localhost“);
writer.println(“connection:keep-alive“);
writer.println();
writer.flush();
//发送请求体
InputStream in=s.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String firstLineOfResponse = reader.readLine();//Content-Type:text/html
String secondLineOfResponse = reader.readLine();//Content-Length
String threeLineOfResponse = reader.readLine();//blank line
String fourLineOfResponse = reader.readLine();//HTTP/1.1 200 OK
//接收响应状态
if((firstLineOfResponse.substring(9 12)).equals(“404“)){
//响应失败
String result = new String();
String line;
while((line = reader.readLine()) != null){
result = result+“\n“+line;
}
System.out.println(result);
reader.close();
writer.close();
}
else{
System.out.println(“请输入保存路径“);
String savelocation = new Scanner(System.in).nextLine();
File fl = new File(savelocation);
if(!fl.exists()){
fl.createNewFile();
}
if(fl.exists()){
byte[] b=new byte[100000];
OutputStream out=new FileOutputStream(savelocation);
int len =in.read(b);
while(len!=-1)
{
out.write(b 0 len);
len = in.read(b);
}
in.close();
out.close();
writer.close();
}
}
s.close();
}
}
catch(UnknownHostException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
}
}
属性 大小 日期 时间 名称
----------- --------- ---------- ----- ----
目录 0 2018-01-19 11:20 实验二\
目录 0 2018-01-19 11:20 实验二\实验二代码\
文件 2413 2017-03-07 17:08 实验二\实验二代码\Client.java
文件 590 2017-03-06 22:15 实验二\实验二代码\Server.java
文件 3894 2017-03-07 17:12 实验二\实验二代码\ServerThread.java
文件 2866 2017-03-07 12:30 实验二\实验二代码\ZipCompressor.java
文件 12956667 2017-03-07 21:31 实验二\董卓然实验二http录屏.mp4
评论
共有 条评论