admin管理员组

文章数量:1389897

I am not sure if this post will be considered as duplicate since the same is on stackoverflow.

I am trying to upload a file to WordPress using REST API. I have tried different headers, values but no luck. I have tried different clients such as okhttp and custom one such as Fast-AndroidNetworking.

I have succeeded to create new post with AndroidNetworking, but when it comes to creating/uploading new media, it does not work and does not return any response.

While doing this post, I was doing testing as well, I figured out that WordPress REST API rejects only images, I could upload other files like pdf, wav and text. With the second code mention below, I could upload txt file, but when I upload big file it throw unknown error. The one million question, if there is an issue with WordPress how PostMan is able to POST media without problem.

Following my code with 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("")
                            .addFileBody(imgFile)
                            .addHeaders("Connection", "keep-alive")
                            .addHeaders("Host", "test.matjri")
                            .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);
            }
    }
}

I have also tried the okhttp instead of AndroidNetworking still no luck to upload, however, I get unknown errors.

The code with 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 = "/";
                    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);
            }
    }
} 

With PostMan the media is upload without any problem, and following is the code generated from 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("")
  .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();

I am not sure if this post will be considered as duplicate since the same is on stackoverflow.

I am trying to upload a file to WordPress using REST API. I have tried different headers, values but no luck. I have tried different clients such as okhttp and custom one such as Fast-AndroidNetworking.

I have succeeded to create new post with AndroidNetworking, but when it comes to creating/uploading new media, it does not work and does not return any response.

While doing this post, I was doing testing as well, I figured out that WordPress REST API rejects only images, I could upload other files like pdf, wav and text. With the second code mention below, I could upload txt file, but when I upload big file it throw unknown error. The one million question, if there is an issue with WordPress how PostMan is able to POST media without problem.

Following my code with 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/wp-json/wp/v2/media")
                            .addFileBody(imgFile)
                            .addHeaders("Connection", "keep-alive")
                            .addHeaders("Host", "test.matjri")
                            .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);
            }
    }
}

I have also tried the okhttp instead of AndroidNetworking still no luck to upload, however, I get unknown errors.

The code with 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/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);
            }
    }
} 

With PostMan the media is upload without any problem, and following is the code generated from 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/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();
Share Improve this question asked Apr 4, 2020 at 20:59 AbdullahAbdullah 1112 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 0

First of all, it is not the fault of AndroidNetworking, it is the permission denied, which I figured out after testing Retrofit, Retrofit throws the error for the permission denied which led me to fix the problem.

I checked above code after fixing the permission and it works very well.

Thank you

PS. There is no need for all the headers, token & Content-Disposition is enough.

本文标签: Create Media via REST API from Android Application