gpt4 book ai didi

java - Android:将视频作为 POST 请求上传到 Java 后端?

转载 作者:行者123 更新时间:2023-12-01 10:06:06 27 4
gpt4 key购买 nike

我只需将视频从我的 Android 设备上传到我的 Java 后端,在阅读了一些 StackOverflow 线程后,我了解到我需要将我的视频作为多部分请求发布到 Java 后端。

我设法实现了以下内容,它基本上将视频文件作为多部分 POST 请求进行 POST。

Android 客户端:

private void uploadVideo(String videoPath) throws ParseException, IOException {

HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("MY_SERVER_URL");

FileBody filebodyVideo = new FileBody(new File(videoPath));
StringBody title = new StringBody("Filename: " + videoPath);
StringBody description = new StringBody("This is a description of the video");

MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("video", filebodyVideo);
reqEntity.addPart("title", title);
reqEntity.addPart("description", description);
httppost.setEntity(reqEntity);

// DEBUG
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();
}

我的问题是,如何从 Java 后端接收文件?这是我需要修改的后端方法。有人可以指出我如何从后端接收视频文件吗?

我现在拥有的:

@Path("/user")
public class UserAPI {

@POST
//To receive the file, What do I add below instead of the lines I've commented.
//@Produces(MediaType.APPLICATION_JSON)
//@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Path("/postvideo")
public VideoResponse PostVideo(){
//My code
}
}

最佳答案

这是我的做法(没有错误处理、验证等)。

@POST
@Path("/")
@Consumes("multipart/form-data")
public Response uploadFileMultipart(MultipartFormDataInput input) {
Map<String, List<InputPart>> uploadForm = input.getFormDataMap();

List<InputPart> inputParts = uploadForm.get("video");

String videoFileName = "GENERATE_YOUR_FILENAME_HERE.mp4";
File file = new File(filename);

if (!file.exists()) {
file.createNewFile();
}

FileOutputStream fop = new FileOutputStream(file);
for (InputPart inputPart : inputParts) {
InputStream inputStream = inputPart.getBody(InputStream.class, null);
byte[] content = IOUtils.toByteArray(inputStream);
fop.write(content);
}

fop.flush();
fop.close();

return Response.status(HttpStatus.SC_OK).build();
}

关于java - Android:将视频作为 POST 请求上传到 Java 后端?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36458541/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com