gpt4 book ai didi

java - 从浏览器发出 GET 请求后通过 java 中的套接字发送文件的正确方法

转载 作者:行者123 更新时间:2023-12-01 17:42:58 26 4
gpt4 key购买 nike

我正在使用浏览器通过简单地输入地址 127.0.0.1:1501/filename.png 来向服务器发送 get 请求。目的是从服务器下载文件。服务器成功接收请求并加载所选文件,它还进入 while 循环并多次执行 print 方法,这意味着正在发送某些内容,但在“网络”选项卡中检查 google chrome 时我只得到 filename.png失败的我不明白为什么这段代码似乎不起作用。print 是一个简单调用 System.out.println() 方法的方法

public class MainClassServer {
public static void main(String[] args){
// TODO Auto-generated method stub
ServerSocket server = null;
try {
server = new ServerSocket();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
server.bind(new InetSocketAddress("127.0.0.1", 1501));
} catch (UnknownHostException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}


while(true) {
String message;
Socket client = null;
print("Waiting for client...");
try{
client = server.accept();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
BufferedReader reader = null;
DataOutputStream writer = null;

try {
reader = new BufferedReader(new InputStreamReader(client.getInputStream()));
writer = new DataOutputStream(new BufferedOutputStream(client.getOutputStream()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
message = reader.readLine();

if(message!=null) {
//I get the correct filename with string manipulation
// I correctly access the file in fact it exist
File file = new File(path);

if(file.exists()) {
byte[] bytes = new byte[1024];
InputStream in = new FileInputStream(path);
int count;
while ((count = in.read(bytes)) > 0) {
//the program print some bytes so it writes something to someone
print("Sending " + count + " bytes");
writer.write(bytes, 0, count);
}
writer.flush();
}else {
print("File does not exsist.");
}


writer.close();
reader.close();
server.close();
break;
}

} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
}


}

最佳答案

浏览器在请求时始终期望返回 HTTP 响应。如果您的客户端是简单的套接字客户端,那么当您在 HTTP 的 DataOutputStream 中编写时,您将获得该文件,至少您需要最小的 HTTP 响应格式。如果您在响应中添加这两个 header ,您可能会得到预期的行为。

if(file.exists()) {
byte[] bytes = new byte[1024];
InputStream in = new FileInputStream(path);
int count;
// Setting HTTP response headers
writer.writeBytes("HTTP/1.0 200 OK\r\n");
writer.writeBytes("Content-Type: image/jpeg\r\n");
writer.writeBytes("\r\n");
while ((count = in.read(bytes)) > 0) {
//the program print some bytes so it writes something to someone
print("Sending " + count + " bytes");
writer.write(bytes, 0, count);
}
writer.flush();
}else {
print("File does not exsist.");
}

关于java - 从浏览器发出 GET 请求后通过 java 中的套接字发送文件的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58755416/

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