简体   繁体   English

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

[英]Error while uploading images to Imgur with api in Android

I am working with the Imgur API for uploading images.我正在使用 Imgur API 上传图片。 The image is clicked using a camera and stored as a bitmap which is further converted into Base-64 String.使用相机单击图像并存储为位图,该位图进一步转换为 Base-64 字符串。

I'm then passing the Base-64 string to a function which should upload the image to Imgur.然后我将 Base-64 字符串传递给一个函数,该函数应该将图像上传到 Imgur。 But the code returns the Error: android.os.NetworkOnMainThreadException但代码返回错误: android.os.NetworkOnMainThreadException

Image capture and convert to Base-64:图像捕获并转换为 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);
            }
        });

Code to upload:上传代码:

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();
        }
    }

I'm using Android Studio and running the app on an AVD (API-30) if that matters.如果重要的话,我正在使用 Android Studio 并在 AVD (API-30) 上运行该应用程序。

Run your upload() function on background thread:在后台线程上运行你的 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);
                    }
                }
            })

Note:The above solution is not the best way of doing async task.The best option is Rxjava/RxAndroid for asynchronous task.注意:以上解决方案不是做异步任务的最佳方式。异步任务的最佳选择是 Rxjava/RxAndroid。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM