从Android应用程序通过REST API创建媒体

时间:2020-04-04 作者:Abdullah

我不确定这篇文章是否会被视为重复,因为stackoverflow也是如此。com。

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

我已经成功地用AndroidNetworking创建了新帖子,但当涉及到创建/上传新媒体时,它不起作用,也不会返回任何响应。

在写这篇文章时,我也在做测试,我发现WordPress REST API只拒绝图像,我可以上传其他文件,如pdf、wav和文本。使用下面提到的第二个代码,我可以上载txt文件,但当我上载大文件时,它会抛出未知错误。一百万个问题,如果WordPress有问题,邮递员如何能够毫无问题地发布媒体。

使用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();

1 个回复
最合适的回答,由SO网友:Abdullah 整理而成

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

在修复权限后,我检查了上面的代码,它运行得很好。

非常感谢。

另外,不需要所有的头、令牌和;内容配置就足够了。

相关推荐

WP media upload issues

我遇到过很多人面临这个问题,最终通过文件许可解决了这个问题。我收到以下错误:上载的文件无法移动到wp content/uploads/sites/2019年4月11日。虽然我已经试过了chmod -r 777 在我的wp内容/上传中,它仍然返回相同的错误。我还添加了wp配置define( \'UPLOADS\', \'wp-content/uploads\' ); require_once( ABSPATH . \'wp-settings.php\' ); 但似乎什么都不管用。