java Servlet做代理转发Protocol Buffer序列化后的数据(httpClient,SmartUpload)

近在用java做一个Web端的小项目,但需要和导师的c++服务交互,于是想到用servlet做代理转发请求,难点在于大多数的转发请求都是对键值对进行转发的,但是我需要转发的是一个二进制的buffer;其包含一个图像文件和一个字符串字段;网上已有的关于httpClient的代码都是比较老的版本,已经不能使用;经过各种尝试,最终得到的解决方案如下:

public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
response.setCharacterEncoding("utf-8");
PrintWriter out = response.getWriter();
try {
SmartUpload smart = new SmartUpload();
// PageContext是jsp的内置对象,在servlet不能直接使用,需要做一些处理
JspFactory _jspxFactory = JspFactory.getDefaultFactory();
PageContext pageContext = _jspxFactory.getPageContext(this, request, response,"", true, 8192, true);
smart.initialize(pageContext);// 初始化上传操作
smart.upload(); 
com.jspsmart.upload.File file=smart.getFiles().getFile(0); 
Classify.ClassRequest.Builder requsetBuilder = Classify.ClassRequest.newBuilder();
String savePathString = request.getSession().getServletContext().getRealPath("")+File.separator + "uploadphoto"
+ File.separator;
File filePath=new File(savePathString);
if (!filePath.exists()) {
filePath.mkdirs();
}

file.saveAs(savePathString+file.getFileName());
File ioFile = new File(savePathString+file.getFileName());
InputStream in = new FileInputStream(ioFile);
byte b[]=new byte[(int)ioFile.length()]; //创建合适文件大小的数组 
in.read(b); //读取文件中的内容到b[]数组 
in.close(); 
requsetBuilder.setData(ByteString.copyFrom(b));
requsetBuilder.setPhotoid(ByteString.copyFromUtf8(file.getFileName()));
Classify.ClassRequest classRequest =requsetBuilder.build();
//创建HttpClientBuilder 
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); 
//HttpClient 
CloseableHttpClient closeableHttpClient = httpClientBuilder.build(); 
HttpPost httpPost=new HttpPost("http://yourip:8080/youtu.ImageClass.classify");
ByteArrayEntity byteArrayEntity=new ByteArrayEntity(classRequest.toByteArray());
httpPost.setEntity(byteArrayEntity);
httpPost.setHeader("Content-Type", "text/html;charset=utf-8");
CloseableHttpResponse httpResponse=closeableHttpClient.execute(httpPost);
//反序列化Buffer
Classify.ClassResponse classResponse=Classify.ClassResponse.parseFrom(EntityUtils.toByteArray(httpResponse.getEntity()));
request.setAttribute("classResponse",classResponse);
request.getRequestDispatcher("../youtuface/classifyresult.jsp").forward(request, response);

} catch (Exception e) {
out.print("{\"Msg\":\"Error! " + e.getMessage()+e.toString() + "\"}");
}
}

 另外由于在一开始实例化HttpPost时误用的是https协议导致出现莫名的错误,调试了大半天都没有解决,最后发现new HttpPost("https:")里面多写了一个s,所以说魔鬼存在于细节中哇。

你可能感兴趣的:(java)