我有这样的Java Web服务器:
public static void main(String[] args) throws Exception {
HttpServer server = HttpServer.create(new InetSocketAddress(80), 0);
server.createContext("/", new HomeHandler());
server.setExecutor(null); // creates a default executor
server.start();
}
而这里的HomeHandler
:
class HomeHandler implements HttpHandler {
public void handle(HttpExchange t) throws IOException {
String filepath = "C:\\Public\\home.html";
String response = getPage(filepath);
t.sendResponseHeaders(200, response.length());
OutputStream os = t.getResponseBody();
os.write(response.getBytes());
os.close();
}
}
最后,这里的功能getPage()
:
private static String getPage(String page){
String toret = "";
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader(page));
while ((sCurrentLine = br.readLine()) != null) {
toret += sCurrentLine;
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null) br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
return toret;
}
但是,当我的主页加载时,它在它有一个像这样的浏览器向我对图像服务器的其他要求,我做了一个类似的处理程序,它做同样的事情的图像,即调用函数GETPAGE()传递的参数图像的文件路径...
但是,当它在浏览器中运行,实际上它不显示图像。但它正确地讲述了图像的大小,当我在新标签页单独打开图像(谷歌Chrome是我的浏览器,最新一期截至今日)..
图像是二进制数据,并且不能经由String
(其不能存储/屈服特定字节序列)被传递。因此,有直接使用byte[]
。尼斯将设置响应类型Content-Type: application/jpeg
或png
或gif
。
顺便说一句,你的代码是用你的平台的编码。对于一个指定的编码,比如通用的Unicode:
getBytes() // Platform dependant
getBytes("UTF-8") // Specified
new FileReader(file) // Platform dependant
new InputStreamReader(new FileInputStream(file),) // Platform dependant
new InputStreamReader(new FileInputStream(file), "UTF-8") // Specified
new FileWriter(file) // Platform dependant
new OutputStreamWriter(new FileOutputStream(file)) // Platform dependant
new OutputStreamWriter(new FileOutputStream(file), "UTF-8") // Specified
byte[] bytes;
new String(bytes) // Platform dependant
new String(bytes, "UTF-8") // Specified
下面是如何实现发回的UI图像的处理程序:
private void forwardImage(HttpExchange exchange, String imagefilename) throws IOException {
byte[] result = readSmallBinaryFile(imagefilename);
if (result == null) {
// resource_not_found_error
}
exchange.getResponseHeaders().set("Content-Type", CONTENT_TYPE_IMG);
OutputStream os = null;
try {
exchange.sendResponseHeaders(200, message.length);
os = exchange.getResponseBody();
os.write(message);
} finally {
os.close();
}
return os;
}