簡體   English   中英

將HTTP標頭添加到Java套接字服務器中的響應

[英]Add HTTP header to response in java socket server

我不確定要在何處或使用什么命令將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標頭,例如,如果發送圖像,則瀏覽器不顯示圖像,而是逐字節顯示。

首選的方法是實現Servlet並在Servlet容器中運行它。 然后,在HttpServletResponse對象上調用方法setHeader

public class ExampleServlet extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
        response.setHeader("X-Whatever-Header-Name-You-Want", "Value");
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM