我正在将视频文件作为多部分请求从我的 Android 客户端发布到我的服务器。我需要编写一个服务器端方法来接收以下请求。
- 我使用 Jersey 作为服务器端框架
我的代码如下:
private void send_video_to_server(String videoPath) throws ParseException, IOException {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://MY_SERVER_URL/videos/postvideo");
FileBody filebodyVideo = new FileBody(new File(videoPath));
StringBody title = new StringBody(titleBox.getText().toString());
StringBody description = new StringBody(captionBox.getText().toString());
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("videoFile", filebodyVideo);
reqEntity.addPart("title", title);
reqEntity.addPart("description", description);
httppost.setEntity(reqEntity);
// DEBUG
System.out.println( "executing request " + httppost.getRequestLine( ) );
HttpResponse response = httpclient.execute( httppost );
HttpEntity resEntity = response.getEntity( );
// DEBUG
System.out.println( response.getStatusLine( ) );
if (resEntity != null) {
System.out.println( EntityUtils.toString( resEntity ) );
} // end if
if (resEntity != null) {
resEntity.consumeContent( );
} // end if
httpclient.getConnectionManager( ).shutdown( );
}
如何编写SERVER端代码来RECEIVE上述请求? 方法签名足以回答:)
最佳答案
问题到底是什么? 不知道 Jersey,但步骤是:
1) 编写一个 servlet ( http://www.tutorialspoint.com/servlets/servlets-first-example.htm )
2) Servlet 输入参数 HttpServletRequest 包含 getParts() 方法,您可以在其中找到您发布的视频...以及其他部分(如果有)
编辑
未经测试,但这对您有帮助吗?您应该能够像这样获取视频数据流。
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
{
Collection parts = req.getParts();
for (Part part : parts) {
//... determine if its a file part from content disposition for example
InputStream is = part.getInputStream();
//...work with your input stream
}
}
详细示例请看spring是如何实现的: See spring way
关于Java:从多部分 POST 请求获取视频文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36486503/