我不确定在哪里或什么命令用于将HTTP标头添加到服务器的响应中。
import java.io.*;
import java.net.*;
import com.sun.net.httpserver.*;
public class Response {
private static final int BUFFER_SIZE = 9999;
Request request;
BufferedOutputStream output;
//constructor para el output
public Response(BufferedOutputStream output){
this.output = output;
}
//Set del request
public void setRequest(Request request){
this.request = request;
}
public void sendResource() throws IOException{
File file = new File(Java_Server.Web_dir,request.getUri());
byte [] bytearray = new byte[(int) file.length()];
FileInputStream file_out = null;
if(file.exists())
file_out = new FileInputStream(file);
else{
String errorMessage = "HTTP/1.1 404 File Not Found\r\n" +
"Content-Type: text/html\r\n" +
"Content-Length: 23\r\n" +
"\r\n" +
"<h1>File Not Found</h1>";
output.write(errorMessage.getBytes());
}
BufferedInputStream bis = new BufferedInputStream(file_out);
try{
bis.read(bytearray,0,bytearray.length);
output.write(bytearray,0 , bytearray.length);
output.flush();
output.close();
return;
}catch (IOException e){
e.printStackTrace();
}
}
内容传递给浏览器,但没有HTTP标头,如果发送图像,浏览器不显示图像,则显示字节为字节。
答案 0 :(得分:0)
首选方法是实现Servlet并在Servlet容器中运行它。然后在setHeader
对象上调用方法HttpServletResponse
:
public class ExampleServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
response.setHeader("X-Whatever-Header-Name-You-Want", "Value");
}
}