62,614
社区成员
发帖
与我相关
我的任务
分享
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();
}
}
}