You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android中无法获取Multipart请求响应问题咨询

Hey there! I’ve worked with net.gotev:uploadservice:2.1 before, so I know exactly how to fix your issue with missing server responses. The thing is, this library handles uploads asynchronously, so you can’t just grab the response right after calling startUpload()—you need to use a BroadcastReceiver to listen for upload completion events and retrieve the server’s reply.

Here’s a step-by-step solution tailored to your code:

1. Create a Custom BroadcastReceiver

This receiver will catch when the upload finishes (success or failure) and give you access to the server response.

public class UploadStatusReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        UploadInfo uploadInfo = intent.getParcelableExtra(UploadService.UPLOAD_INFO);

        if (UploadService.BROADCAST_ACTION_UPLOAD_COMPLETE.equals(action)) {
            // Get the server's response data
            String serverResponse = uploadInfo.getServerResponse();
            int statusCode = uploadInfo.getHttpStatusCode();

            // Handle the response here (update UI, parse JSON, etc.)
            if (statusCode == HttpURLConnection.HTTP_OK) {
                Toast.makeText(context, "Upload succeeded! Response: " + serverResponse, Toast.LENGTH_LONG).show();
                // Example: Parse JSON response if needed
                // YourJsonModel model = new Gson().fromJson(serverResponse, YourJsonModel.class);
            } else {
                Toast.makeText(context, "Upload failed. Status code: " + statusCode, Toast.LENGTH_LONG).show();
            }

        } else if (UploadService.BROADCAST_ACTION_UPLOAD_ERROR.equals(action)) {
            // Handle upload errors
            String errorMsg = uploadInfo.getErrorMessage();
            Toast.makeText(context, "Upload error: " + errorMsg, Toast.LENGTH_LONG).show();
        }
    }
}

2. Register the Receiver in Your Activity

You need to register this receiver dynamically in your activity to listen for the upload events. Don’t forget to unregister it to avoid memory leaks!

private UploadStatusReceiver uploadReceiver;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.your_activity_layout);

    // Initialize and register the receiver
    uploadReceiver = new UploadStatusReceiver();
    IntentFilter filter = new IntentFilter();
    filter.addAction(UploadService.BROADCAST_ACTION_UPLOAD_COMPLETE);
    filter.addAction(UploadService.BROADCAST_ACTION_UPLOAD_ERROR);
    registerReceiver(uploadReceiver, filter);

    // Your existing upload code (updated for clarity)
    try {
        String uploadId = UUID.randomUUID().toString();
        new MultipartUploadRequest(getActivity(), uploadId, "http://your-server-url")
                .addFileToUpload("/sdcard/your-image.jpg", "image") // Replace with your file path and param name
                .addParameter("user_id", "123") // Add your custom parameters
                .addParameter("description", "Sample image upload")
                .setMaxRetries(2) // Optional: Set retry count for failed uploads
                .startUpload(); // Kick off the upload
    } catch (Exception e) {
        e.printStackTrace();
        Toast.makeText(this, "Failed to initialize upload: " + e.getMessage(), Toast.LENGTH_SHORT).show();
    }
}

@Override
protected void onDestroy() {
    super.onDestroy();
    // Unregister the receiver to prevent memory leaks
    if (uploadReceiver != null) {
        unregisterReceiver(uploadReceiver);
    }
}

Key Notes to Remember:

  • Make sure your server is actually sending a response body (e.g., JSON, plain text) — uploadInfo.getServerResponse() will only return content if the server sends it.
  • For Android 7.0+, dynamic registration (like we did here) is more reliable than static registration in the manifest, as system restrictions on implicit broadcasts apply.
  • If your response is JSON, use a library like Gson or Moshi to parse serverResponse into a model class for easier handling.

That should do it! You’ll now be able to capture the server’s response every time an upload completes.

内容的提问来源于stack exchange,提问作者D Developer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 07:34:42