轻量型Java服务器关于响应的问题

ShyLbi 2017-11-22 11:16:25
1下面是我响应的客户端的代码
package tedu.cn.com.tedu.http;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

public class HttpResponse {
private OutputStream out;
private File entity;
private Map<String,String> headers=new HashMap<String,String>();

public File getEntity() {
return entity;
}
public void setEntity(File entity) {
this.entity = entity;
}

public void setContentType(String contentType){
headers.put("Content-Type", contentType);
}

public void setContentLength(int length){
headers.put("Content-Length",length+"");
}

public HttpResponse(OutputStream out){
this.out=out;
}

public void flush(){
sendStatusLine();
sendHeaders();
sendContent();
}

public void sendStatusLine(){
println("HTTP/1.1 200 OK");
System.out.println("响应头发送完毕");
}

public void sendHeaders(){
Set<Entry<String,String>> headersSet=headers.entrySet();
for(Entry<String,String> header:headersSet){
String key=header.getKey();
String value=header.getValue();
String line=key+":"+value;
System.out.println(line);
println(line);
}
println("");
System.out.println("响应行发送完毕");
}

public void sendContent(){
try {
FileInputStream fis=new FileInputStream(entity);
byte[] data=new byte[1024];
int len=-1;
try {
while((len=fis.read(data))!=-1){
out.write(data, 0, len);
}
System.out.println("文件发送成功");
} catch (IOException e) {
e.printStackTrace();
}finally{
if(fis!=null){
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}

public void println(String line){
try {
out.write(line.getBytes("ISO8859-1"));
out.write(HttpContext.CR);
out.write(HttpContext.LF);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

}

2这是网页的反应

3这是输出到网页的源码

是在是不知道哪里出了问题,建的是Maven项目,不知道是不是构建的时候错了
...全文
183 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
ShyLbi 2017-11-24
  • 打赏
  • 举报
回复
已经解决了,原因是响应的时候ContentLength设置成文件名的长度,没有设置成文件大小的长度,所以一直没有发出去,
  • 打赏
  • 举报
回复
这个说明的不是很清楚,,,,还是详细说说你是怎么去实现的吧

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧