在 Android 中使用 api 将图像上传到 Imgur 时出错

Error while uploading images to Imgur with api in Android

我正在使用 Imgur API 上传图片。使用相机点击图像并存储为位图,位图进一步转换为 Base-64 字符串。

然后我将 Base-64 字符串传递给一个函数,该函数应该将图像上传到 Imgur。但是代码 returns 报错: android.os.NetworkOnMainThreadException

图像捕获并转换为 Base-64:

ActivityResultLauncher<Intent> someActivityResultLauncher = registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(),
                new ActivityResultCallback<ActivityResult>() {
                    @Override
                    public void onActivityResult(ActivityResult result) {
                        if (result.getResultCode() == Activity.RESULT_OK) {
                            //Bitmap part
                            Intent data = result.getData();
                            Bitmap captureImage=(Bitmap) data.getExtras().get("data");
                            //Base-64 part 
                            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                            captureImage.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
                            byte[] byteArray = byteArrayOutputStream .toByteArray();
                            String encoded = Base64.encodeToString(byteArray, Base64.DEFAULT);

                            upload(encoded);
                            //profilePic.setImageBitmap(captureImage);
                        }
                    }
                });
        imageButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //Camera Capture
                Intent intent=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                someActivityResultLauncher.launch(intent);
            }
        });

要上传的代码:

public void upload(String encoded){
        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        MediaType mediaType = MediaType.parse("text/plain");
        RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)
                .addFormDataPart("image",encoded)
                .build();
        Request request = new Request.Builder()
                .url("https://api.imgur.com/3/image")
                .method("POST", body)
                .addHeader("Authorization", "Client-ID {{MY_ID}}")
                .build();
        try {
            Response response = client.newCall(request).execute();
            Log.wtf("RESPONSE",""+response);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

如果重要的话,我正在使用 Android Studio 和 运行 AVD (API-30) 上的应用程序。

运行 您在后台线程上的 upload() 函数:

ActivityResultLauncher<Intent> someActivityResultLauncher = registerForActivityResult(
            new ActivityResultContracts.StartActivityForResult(),
            new ActivityResultCallback<ActivityResult>() {
                @Override
                public void onActivityResult(ActivityResult result) {
                    if (result.getResultCode() == Activity.RESULT_OK) {
                        //Bitmap part
                        Intent data = result.getData();
                        Bitmap captureImage=(Bitmap) data.getExtras().get("data");
                        //Base-64 part 
                        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                        captureImage.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
                        byte[] byteArray = byteArrayOutputStream .toByteArray();
                        String encoded = Base64.encodeToString(byteArray, Base64.DEFAULT);

new Thread(new Runnable() {
@Override
public void run() {
    upload(encoded);  //background stuff
    runOnUiThread(new Runnable() {
        public void run() {
            // do onPostExecute stuff
        }
    });
}
}).start();                        
                        //profilePic.setImageBitmap(captureImage);
                    }
                }
            })

注意:上述解决方案不是执行异步的最佳方法task.The对于异步任务,最佳选择是Rxjava/RxAndroid。