I would like to know why I can successfully upload a file to a server using AsyncHttpClient
but not when using SyncHttpClient
.
The following setting yields successful result:
MultipartEntityBuilder
to build my multipart upload request +AsyncHttpClient
to post it. Posting the request is triggered by tapping a button in the activity.
However, because I want to upload in an IntentService
, I use SyncHttpClient
, and the following setting does not successfully upload the file.
MultipartEntityBuilder
+SyncHttpClient
+IntentService
.
Below is how I build and send my request, which is the same in settings 1 and 2. The upload
method is placed inside a helper class. And is invoked on a singleton instance, which when constructed its mContext
is also set. client
is a static instance variable of the helper class; client
is a AsyncHttpClient
in setting 1 and a SyncHttpClient
in setting 2.
// MyUploadHelper.java
public void upload(File f) {
String fileName = file.getName();
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addTextBody("api", "SYNO.FileStation.Upload");
// some more addTextBody omitted
builder.addBinaryBody("filename", file, ContentType.APPLICATION_OCTET_STREAM, fileName);
HttpEntity entity = builder.build();
client.post(mContext, getAbsoluteUrl(),
entity, "multipart/form-data",
new JsonHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
// This part can be reached in both settings. But in setting 2, the server returns "Unknown error of file operation".
}
});
}
The method is called this way:
MyUploadHelper.getInstance(this).upload(aFile);
where this
is an Activity
in Setting 1 and an IntentService
in Setting 2.
Finally, Happy New Year in advance!