【问题标题】:Error while uploading images to Imgur with api in Android在 Android 中使用 api 将图像上传到 Imgur 时出错
【发布时间】:2021-12-06 10:02:56
【问题描述】:

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

然后我将 Base-64 字符串传递给应该将图像上传到 Imgur 的函数。但代码返回错误: 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()函数。或者,使用 Retrofit 之类的东西来创建您的 API 请求。 related docs
  • @rupinderjeet 对不起,什么是后台线程?
  • 主线程负责绘制你的 UI(活动、片段、视图)。 Android 不允许你在这个线程上执行网络请求,因为这些请求会阻塞主线程。因此,相反,我们使用一个后台线程来执行 CPU 或 I/O 任务,而不会影响应用程序的 UI 和动画。 Read this blog post 知道为什么。

标签: java android imgur networkonmainthread


【解决方案1】:

在后台线程上运行您的 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);
                    }
                }
            })

注意:上述方案并不是做异步任务的最佳方式。异步任务最好的选择是Rxjava/RxAndroid。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-04-25
    • 1970-01-01
    • 2011-05-20
    • 1970-01-01
    • 2019-07-05
    • 2016-07-17
    • 2016-01-11
    • 2015-03-12
    相关资源
    最近更新 更多