Я пытаюсь загрузить файл в WordPress с помощью REST API. Я пробовал разные заголовки, значения, но не повезло. Я пробовал разные клиенты, такие как 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();