服务器通过IO流响应图片数据
在上一篇文章里,介绍了Android客户端如何通过IO流(http://blog.csdn.net/ceovip/article/details/79100368),从服务器获取图片数据。这里的服务器端测试代码比较简单,示例如下:
package com.li.downloadtest;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class DownloadServlet extends HttpServlet {
/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
@SuppressWarnings("static-access")
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//读取输入流数据
ServletInputStream is = request.getInputStream();
BufferedReader bufRd = new BufferedReader(new InputStreamReader(is, "UTF-8"));
StringBuffer strBuf = new StringBuffer();
String strContent = new String("");
while((strContent = bufRd.readLine()) != null){
strBuf.append(strContent);
}
//获取请求参数
String jsStr = strBuf.toString();
System.out.println("param--->" + jsStr);
//输出图片数据
try {
response.setContentType("image/jpeg;charset=UTF-8");
OutputStream out = response.getOutputStream();
String imgUrl = "C:\\Users\\lish\\Desktop\\test.jpg";
FileInputStream fis = new FileInputStream(imgUrl);
int len = -1;
byte[] data = new byte[1024];
while((len = fis.read(data)) != -1){
out.write(data, 0 , len);
}
fis.close();
out.close();
} catch (Exception e) {
PrintWriter writer = response.getWriter();
response.setContentType("text/html;charset=UTF-8");
writer.write("无法打开图片!");
writer.close();
}
}
}