问题描述
我正在编写一段代码来执行多部分表单数据 POST 请求,在我的情况下,这只是将带有参数的图像上传到服务器.这是我现在所拥有的:
I am working on a piece of code to do multipart form data POST request, which in my case is just to upload an image to server with parameters. Here's what I have now:
我有一个按钮来触发多部分请求,在按钮 OnClickListener 中,我有这个代码来旋转一个新线程:
I have a button to trigger the multipart request, in the button OnClickListener, I have this code to spin a new thread:
new Thread(new Runnable(){
@Override
public void run() {
String photoUri = getPhotoUri();
String url = getEndPointUrl();
try {
NewPostRequest.postFile(url, photoUri, <Other Params...>);
} catch (Exception e) {
// Exception Handling
}
}).start();
而 NewPostRequest.postFile
只是使用 Apache Http Client 来发出请求,基本上如下:
And the NewPostRequest.postFile
is just using Apache Http Client to make a request, basically like below:
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
File file = new File(fileUri);
FileBody fb = new FileBody(file);
builder.addPart("file", fb);
builder.addTextBody("param", otherParam);
HttpEntity entity = builder.build();
post.setEntity(entity);
HttpResponse response = client.execute(post);
我每次都需要旋转一个新线程,因为最近的 Android 版本不允许程序在 UI 线程上发出 http 请求.但是,我真的反对像上面的代码一样旋转随机线程并让它失控.我曾尝试使用 Google Volley 库,但它不是少数工具上传图片等大数据文件.
I need to spin a new thread everytime because the recent Android releases doesn't let program to make http requests on UI thread. However, I really against to spin a random thread and let it out of control like the code above. I have tried to use Google Volley library, but it is not a handful tool when uploading large data files like image.
我想知道我应该怎么做才能使这个调用更易于管理?
I was wondering what I should do to make this call more manageable?
====== 更新 ======
===== UPDATE =====
我改用了 AsyncTask,现在它工作正常.我会保留这个问题,看看是否有人有更好的方法.
I switched to use AsyncTask and it works OK for now. I will keep this question open to see if any one has better approach.
推荐答案
HTTP 一直是 Android 的痛点.幸运的是,我们有许多很棒的库来处理所有困难的部分.
HTTP has always been a pain point in Android. Fortunately, we have many great libraries that take care of all the hard parts.
试用 Ion.
它允许您在后台线程中轻松执行多部分请求,并让您在请求完成时在主线程上获得回调.
It allows you to easily do Multi-Part requests in a background thread and let's you get callbacks on the main thread when the request is complete.
它还做其他很酷的事情,比如智能缓存、当调用上下文超出范围时自动取消请求等.
It also does other cool stuff like intelligent caching, automatic request cancellation when the calling Context goes out of scope etc.
P.S:Retrofit 是另一个很棒的库,但我自己更喜欢 Ion.只是喜好问题.
P.S: Retrofit is another great library but I prefer Ion myself. Just a matter of preference.
这篇关于在Android中进行分段文件上传的好方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!