【问题标题】:Upload File via WordPress REST API from Android Application从 Android 应用程序通过 WordPress REST API 上传文件
【发布时间】:2020-04-04 16:20:10
【问题描述】:

我正在尝试使用 REST API 将文件上传到 WordPress。我尝试了不同的标题、值但没有运气。我尝试过不同的客户端,例如 okhttp 和自定义客户端,例如 Fast-AndroidNetworking。

我已成功使用 AndroidNetworking 创建新帖子,但在创建/上传新媒体时,它不起作用并且没有返回任何响应。

上传失败。

使用 AndroidNetworking 跟踪我的代码。

public class MainActivity extends AppCompatActivity {

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

        Button btnImage = findViewById(R.id.button);

        btnImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                intent.setType("image/*");
                startActivityForResult(intent, 1234);
            }
        });

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        ImageView imgTestImage = findViewById(R.id.imageView1);
        final TextView txtTestPath = findViewById(R.id.txtTestPath);

        if (resultCode == Activity.RESULT_OK)
            switch (requestCode){
                case 1234:
                    Uri uriSelectedImage = data.getData();
                    String imgFullPath = uriSelectedImage.getPath();

                    String imgPath = imgFullPath.substring(imgFullPath.lastIndexOf(":")+1);

                    File imgFile = new File(imgPath);
                    String imgName = imgFile.getName();
                    long imgSize = imgFile.length();
                    String mimType = getContentResolver().getType(uriSelectedImage);

                    txtTestPath.setText(imgPath +"\n"+mimType + "\n"+ imgName + " "+ String.valueOf(imgSize));


                    AndroidNetworking.initialize(getApplicationContext());
                    AndroidNetworking.post("https://test.matjri.com/wp-json/wp/v2/media")
                            .addFileBody(imgFile)
                            .addHeaders("Connection", "keep-alive")
                            .addHeaders("Host", "test.matjri.com")
                            .addHeaders("Content-Length", String.valueOf(imgSize))
                            .addHeaders("Cache-Control", "no-cache")
                            .addHeaders("Content-Type", mimType)
                            .addHeaders("Content-Disposition", "attachment;filename=\"" + imgName + "\"")
                            .addHeaders("Authorization", "Bearer mytoken")
                            .setTag("uploadFile")
                            .setPriority(Priority.MEDIUM)
                            .build()
                            .getAsJSONObject(new JSONObjectRequestListener() {

                                @Override
                                public void onResponse(JSONObject response) {
                                    txtTestPath.setText(response.toString());
                                }
                                @Override
                                public void onError(ANError anError) {

                                    txtTestPath.setText(anError.getMessage());
                                }
                            });




                    imgTestImage.setImageURI(uriSelectedImage);
            }
    }
}

我也尝试了 okhttp 而不是 AndroidNetworking 仍然无法上传,但是,我收到未知错误。

okhttp的代码

public class MainActivity extends AppCompatActivity {

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

        Button btnImage = findViewById(R.id.button);

        btnImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                intent.setType("image/*");
                startActivityForResult(intent, 1234);
            }
        });

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        ImageView imgTestImage = findViewById(R.id.imageView1);
        final TextView txtTestPath = findViewById(R.id.txtTestPath);

        if (resultCode == Activity.RESULT_OK)
            switch (requestCode){
                case 1234:
                    Uri uriSelectedImage = data.getData();
                    String imgFullPath = uriSelectedImage.getPath();

                    String imgPath = imgFullPath.substring(imgFullPath.lastIndexOf(":")+1);

                    File imgFile = new File(imgPath);
                    String imgName = imgFile.getName();
                    long imgSize = imgFile.length();
                    String mimType = getContentResolver().getType(uriSelectedImage);

                    txtTestPath.setText(imgPath +"\n"+mimType + "\n"+ imgName + " "+ String.valueOf(imgSize));
                    OkHttpClient okHttpClient = new OkHttpClient();

                    MultipartBody.Builder builder = new MultipartBody.Builder();
                    builder.setType(MultipartBody.FORM);
                    builder.addFormDataPart("file", imgPath);

                    String url = "https://test.matjri.com/wp-json/wp/v2/media/";
                    RequestBody fileBody = RequestBody.create(MediaType.parse(mimType), imgPath);
                    builder.addFormDataPart("file", imgName, fileBody);
                    RequestBody requestBody = builder.build();
                    Request request = new Request.Builder()
                            .url(url)
                            .addHeader("Authorization", "Bearer  mytoken")
                            .addHeader("Content-Type", mimType)
                            .addHeader("Content-Length", String.valueOf(imgSize))
                            .addHeader("Content-Disposition", "attachment; filename=\"maroof.png\"")
                            .post(requestBody)
                            .build();
                    okHttpClient.newCall(request).enqueue(new okhttp3.Callback(){
                        @Override
                        public void onFailure(Call call, IOException e) {
                            Log.e("OkHttp1", "onFailure: "+e.toString());
                        }

                        @Override
                        public void onResponse(Call call, Response response) throws IOException {
                            ResponseBody body = response.body();
                            if (body != null) {
                                txtTestPath.setText(body.string());
                            } else {
                                Log.e("OkHttp1", "onResponse: null");
                            }
                        }
                    });


                    imgTestImage.setImageURI(uriSelectedImage);
            }
    }
} 

使用 PostMan 上传媒体没有任何问题,下面是 PostMan 生成的代码。

OkHttpClient client = new OkHttpClient().newBuilder()
  .build();
MediaType mediaType = MediaType.parse("text/plain");
RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)
  .addFormDataPart("file","/C:/Users/Abdul/OneDrive - OkamKSA/Alahdal/Personal/Web/SS/maroof.png",
    RequestBody.create(MediaType.parse("application/octet-stream"),
    new File("/C:/Users/Abdul/OneDrive - OkamKSA/Alahdal/Personal/Web/SS/maroof.png")))
  .build();
Request request = new Request.Builder()
  .url("https://test.matjri.com/wp-json/wp/v2/media")
  .method("POST", body)
  .addHeader("Authorization", "Bearer mytoken")
  .addHeader("Cookie", "wp-wpml_current_admin_language_d41d8cd98f00b204e9800998ecf8427e=ar; _mcnc=1")
  .build();
Response response = client.newCall(request).execute();

【问题讨论】:

  • 我收到了更新,但是,我不想将其视为答案,因为它不能完全解决它。使用 OP 中的第二个代码,我可以发布一个 txt 文件,这似乎是 WordPress 的问题。另一个,第二个代码的问题,我注意到当我上传大文件时,它会断开连接并抛出未知错误。
  • 问题仍然存在,PostMan 如何能够毫无问题地上传图片。

标签: android wordpress rest api


【解决方案1】:

首先,这不是AndroidNetworking的错,是权限被拒绝,我在测试Retrofit后发现,Retrofit抛出权限被拒绝的错误导致我修复了问题。

我在修复权限后检查了上面的代码,效果很好。

谢谢

PS。不需要所有的 headers,token & Content-Disposition 就足够了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-10
    • 2017-11-23
    • 1970-01-01
    • 2021-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-30
    相关资源
    最近更新 更多