Bad request while sending multpart image through retrofit 2.1.0 - android

private void saveImageToServer(final String savedpath) {
showLoader();
NetworkUtil.checkInternetConnection(DetailActiveSRActivity.this, new NetworkUtil.NetworkStatusListener() {
#Override
public void onNetworkAvailable() {
File file = new File(savedpath);
// RequestBody requestFile = RequestBody.create(MediaType.parse("image/jpeg"), savedpath);
RequestBody requestFile = RequestBody.create(MediaType.parse("image/*"), file);
Log.e(TAG, "onNetworkAvailable: requestFIle " + savedpath+"\n"+" file "+file);
MultipartBody.Part body = MultipartBody.Part.createFormData("image", file.getName(), requestFile);
Log.e(TAG, "onNetworkAvailable: body " + body);
RequestBody reqUserId = RequestBody.create(MediaType.parse("text/plain"), userId);
//RequestBody reqImageType =RequestBody.create(MediaType.parse("text/plain"), "1");
Call<SaveImageResponseModel> responseCall = mService.saveImages(body, reqUserId);
responseCall.enqueue(new Callback<SaveImageResponseModel>() {
#Override
public void onResponse(Call<SaveImageResponseModel> call, retrofit2.Response<SaveImageResponseModel> response) {
hideLoader();
if (response != null) {
SaveImageResponseModel apiResponse = response.body();
if (apiResponse != null && apiResponse.getStatus()) {
Log.e(TAG, "onRequestSuccess: " + apiResponse);
} else {
Toast.makeText(DetailActiveSRActivity.this, getString(R.string.noDataError), Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(DetailActiveSRActivity.this, getString(R.string.noDataError), Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<SaveImageResponseModel> call, Throwable t) {
hideLoader();
}
});
}
#Override
public void onNetworkNotAvailable() {
Toast.makeText(DetailActiveSRActivity.this, getString(R.string.noNetworkMessage), Toast.LENGTH_SHORT).show();
hideLoader();
}
});
}
#Headers({
"authkey: ABCD#123"
})
#Multipart
#POST(UrlUtils.POST_IMAGES)
Call<SaveImageResponseModel> saveImages(#Part MultipartBody.Part file, #Part("userId") RequestBody userId);

First of all, no description, please add a little bit more.
Second:
show what is the content of mService.saveImages(body, reqUserId);
is the HTTP call of POST type?
is the endpoint really working? You should for example try to make call through Postman and you'll see, if it is going through

Related

File upload using retrofit android?

I am trying to upload a video file using multipart by retrofit and I get the following error in response
Response{protocol=http/1.1, code=405, message=Method Not Allowed, url=serverurl/Upload/Videos/}
This is my code for file upload
void uploadVideo(String videoPath) {
dialog.show();
File videoFile = new File(videoPath);
RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), videoPath);
MultipartBody.Part vFile = MultipartBody.Part.createFormData("file", videoFile.getName(), requestFile);
apiCall.uploadVideoToServer(presenter.getUserInfo().getUploadVideoPath(), vFile).enqueue(new Callback<String>() {
#Override
public void onResponse(Call<String> call, Response<String> response) {
dialog.dismiss();
}
#Override
public void onFailure(Call<String> call, Throwable t) {
dialog.dismiss();
}
});
}
This is the path I am uploading the file to
http://serverurl.com/Upload/Videos/
Can someone tell me whats wrong with my code?
Retrofir API interface
#Multipart
#POST
Call<String> uploadVideoToServer(#Url String url, #Part MultipartBody.Part video);
in your api service interface :
#Multipart
#POST("Upload/Videos") // *** DONT FORGET UR END POINT HERE ***
Call<urmodel> uploadVideoToServer(#PartMap Map<String, RequestBody> map);
and write a method to upload ur video file like this :
private void uploadVideoToServer(String path) {
File videoFile = new File(path);
if (videoFile.exists()) {
//create request body
Map<String, RequestBody> map = new HashMap<>();
RequestBody requestBody = RequestBody.create(MediaType.parse("video/*"), videoFile);
map.put("video\"; filename=\"" + videoFile.getName() + "\"", requestBody);
//make call
Call<urmodel> call = mTService.uploadVideoToServer(map);
call.enqueue(new Callback<urmodel>() {
#Override
public void onResponse(Call<urmodel> call, Response<urmodel> response) {
if (response.isSuccess()) {
// DO SOMETHING
} else {
// DO SOMETHING
}
}
#Override
public void onFailure(Call<urmodel> call, Throwable t) {
//occur when fail to deserialize || no network connection || server unavailable
Toast.makeText(getBaseContext(), "Fail it >> " + t.getMessage(), Toast.LENGTH_LONG).show();
}
});
} else {
Toast.makeText(getBaseContext(), "can not upload file since the file is not exist :|", Toast.LENGTH_SHORT).show();
}
}

Upload file to server using retrofit

How to make request from retrofit android if the request to server looks like in the image.
Well, you could search about this before posting, quite sure you could have found something already, but..
#Multipart
#POST(RestClient.UPDATE_USER_PICTURE)
Call<BooleanResponse> updateUserPicture(#Part MultipartBody.Part picture, #Part("picture") RequestBody file);
Above part is the retrofit interface method that you'll use
RequestBody reqFile = RequestBody.create(MediaType.parse("multipart/form-data"), loadImageFile);
MultipartBody.Part filePart = MultipartBody.Part.createFormData("picture", loadImageFile.getName(), reqFile);
RequestBody filename = RequestBody.create(MediaType.parse("text/plain"), loadImageFile.getName());
RestClient.getApi().updateUserPicture(filePart, filename).enqueue(new Callback<BooleanResponse>() {
#Override
public void onResponse(Call<BooleanResponse> call, Response<BooleanResponse> response) {
if (response.isSuccessful() && response.code() == 200){
Toast.makeText(CompleteProfile.this, "Picture updated successfully!", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<BooleanResponse> call, Throwable t) {
Toast.makeText(CompleteProfile.this, "Request failed !" + t.getMessage(), Toast.LENGTH_SHORT).show();
Log.e(TAG, "-=onFailure=-\n" + t.getMessage(), t);
}
});

My ProgressDialog is Not Disappearing

I am working on a project in android to upload a file to server using file chooser But there is a problem, when i am Uploading more than 500 kB file. The file is uploaded but My Progress Dialog is not disappearing and if i uploaded file 100 KB it's uploaded to server and i got a message file uploaded successfully. But I'm not able to get server response if i uploaded more than 500 kB file. Please Help me. Thank You.
It's my UploadFile() Methods
private void uploadFile() {
dialog = ProgressDialog.show(getActivity(), "", "Uploading File...", true);
// Map is used to multipart the file using okhttp3.RequestBody
Map<String, RequestBody> map = new HashMap<>();
long maxLength = 10000000;
File file = new File(selectedFilePath);
if(file.length() > maxLength){
Toast.makeText(getActivity(), "can't upload file if size more than 10mb", Toast.LENGTH_LONG).show();
dialog.dismiss();
}else {
String name = tv_name.getText().toString();
String email = tv_email.getText().toString();
// Parsing any Media type file
RequestBody requestBody = RequestBody.create(MediaType.parse("*/*"), file);
RequestBody requestBody1 = RequestBody.create(MediaType.parse("text/plain"), name);
RequestBody requestBody2 = RequestBody.create(MediaType.parse("text/plain"), email);
map.put("file\"; filename=\"" + selectedFilePath + "\"", requestBody);
map.put("name\"; username=\"" + name + "\"", requestBody1);
map.put("email\"; email=\"" + email + "\"", requestBody2);
ApiConfig getResponse = AppConfig.getRetrofit().create(ApiConfig.class);
Call<ServerResponse> call = getResponse.upload("token", map);
call.enqueue(new Callback<ServerResponse>() {
#Override
public void onResponse(Call<ServerResponse> call, Response<ServerResponse> response) {
ServerResponse serverResponse = response.body();
if (serverResponse != null) {
if (serverResponse.getSuccess()) {
Toast.makeText(getActivity(), serverResponse.getMessage(), Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getActivity(), serverResponse.getMessage(), Toast.LENGTH_SHORT).show();
}
} else {
// Log.v("Response", serverResponse.toString());
}
dialog.dismiss();
goToProfile();
}
#Override
public void onFailure(Call<ServerResponse> call, Throwable t) {
}
});
}
}
When you get response you have to dismiss your progress dialog.
Example:
if (cls_networlconnection.isOnline())
{
progressdialog = ProgressDialog.showdialog(this,"Loading");
APICall();
}
else {
Toast.makeText(getApplicationContext(),UserToastMessage.NETWORKCONNECTION, Toast.LENGTH_LONG).show();
callNoconnection();
}
API Call Success()
{
if(progressDialog.isShowing)
progressDialog.dismiss();
//your logic
}
Update your onFailure code :
#Override
public void onFailure(Call<ServerResponse> call, Throwable t) {
dialog.dismiss();
}
Also in onResponse, first you need to dismiss dialog :
#Override
public void onResponse(Call<ServerResponse> call, Response<ServerResponse> response) {
if(progressDialog.isShowing){
dialog.dismiss();
}
ServerResponse serverResponse = response.body();
if (serverResponse != null) {
if (serverResponse.getSuccess()) {
Toast.makeText(getActivity(), serverResponse.getMessage(), Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getActivity(), serverResponse.getMessage(), Toast.LENGTH_SHORT).show();
}
} else {
// Log.v("Response", serverResponse.toString());
}
goToProfile();
}

Retrofit 2 : send files with json object

I'm sending object in request body, something like that :
{
"title":"test",
"description":"test",
"images":[]
}
#POST("create-data")
Call<JsonObject> publishData(#Body MyObject object);
and it's work fine without the images. From the docs I can find how to upload file to server using MultipartBody.Part, my questions is :
How can I upload multiple images at the same time?
Is it possible to send the images inside the object, or I need to send it separately and how ?
thank you very much.
request success just now with server
I reference the article:
https://futurestud.io/blog/retrofit-2-how-to-upload-files-to-server
#Multipart
#POST("uploadHeadPic")
Call<UploadHeadPicResponseModel> uploadHeadPic(#Part MultipartBody.Part file, #Part("json") RequestBody json);
public void doUploadHeadPic(#NonNull String filePath) {
if (!MNetworkUtil.isNetworkAvailable()) {
MToastUtil.show("网络不能连接");
return;
}
File file = new File(filePath);
String json = new Gson().toJson(new UploadHeadPicRequestModel());
if (!file.exists()) {
MToastUtil.show("文件不存在");
return;
}
progressDialog.show();
avatarSimpleDraweeView.setEnabled(false);
MApiManager.getService().uploadHeadPic(
MultipartBody.Part.createFormData("file", file.getName(), RequestBody.create(MediaType.parse("multipart/form-data"), file)),
RequestBody.create(MediaType.parse("multipart/form-data"), json))
.enqueue(new OnRetrofitCallbackListener<UploadHeadPicResponseModel>(mActivity) {
#Override
public void onSuccess(UploadHeadPicResponseModel responseModel) {
progressDialog.dismiss();
avatarSimpleDraweeView.setEnabled(true);
if (responseModel != null) {
String serverAvatarUrl = responseModel.data.headPicPath;
if (!TextUtils.isEmpty(serverAvatarUrl)) {
UserModel userModel = MUserManager.getInstance().getUser();
if (userModel != null) {
userModel.setAvatarUrl(serverAvatarUrl);
MUserManager.getInstance().updateOrInsertUserInfo(userModel);
MToastUtil.show("上传头像成功");
}
}
}
}
#Override
public void onFailure(int status, String failureMsg) {
progressDialog.dismiss();
avatarSimpleDraweeView.setEnabled(true);
MToastUtil.show((TextUtils.isEmpty(failureMsg) ? "上传失败" : failureMsg) + " : " + status);
}
});
}
update for multi files
may be this could help , I did not try
#Multipart
#POST("uploadHeadPic")
Call<UploadHeadPicResponseModel> uploadHeadPic(#Part MultipartBody.Part file0, #Part MultipartBody.Part file1, #Part("json") RequestBody json);
public void doUploadHeadPic(#NonNull String filePath) {
MApiManager.getService().uploadHeadPic(
MultipartBody.Part.createFormData("file0", file0.getName(), RequestBody.create(MediaType.parse("multipart/form-data"), file0)),
MultipartBody.Part.createFormData("file1", file1.getName(), RequestBody.create(MediaType.parse("multipart/form-data"), file1)),
RequestBody.create(MediaType.parse("multipart/form-data"), json))
.enqueue(new OnRetrofitCallbackListener<UploadHeadPicResponseModel>(mActivity) {
#Override
public void onSuccess(UploadHeadPicResponseModel responseModel) {
}
#Override
public void onFailure(int status, String failureMsg) {
}
});
}
In my case (uploading to server built with Spring) I needed to change MediaType for RequestBody:
RequestBody.create(MediaType.parse("application/json"), json)
RequestBody.create(MediaType.parse("image/jpg"), file)

Upload file in Retrofit 2

I tried the following but on response i am getting 500 error (Internal Server Error) -- help me design the interface for the request in the above screenshot...thanks
#Multipart
#POST("myrecord")
Call<ResponseBody> addRecord(#Query("token") String token,#Query("userid") int userId,
#Query("name") String name, #Part("file") RequestBody file);
File file = new File(getRealPathFromURI(data.getData()));
RequestBody requestFile = RequestBody.create(MediaType.parse("image/*"), getRealPathFromURI(data.getData()));`
Call<ResponseBody> responseBodyCall = service.addRecord(token, userId,
"newFileName", requestFile);
responseBodyCall.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
Log.d("Response", "="+response.code());
Log.d("Response", "= "+response.message());
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Log.d("failure", "message = " + t.getMessage());
Log.d("failure", "cause = " + t.getCause());
}
});`
The following code worked :)
#Multipart
#POST("myrecord")
Call<ResponseBody> addRecord(#Query("token") String token, #Query("userid") int userId,
#Query("name") String name, #Part MultipartBody.Part file);
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if ((requestCode == FILE_SELECT_CODE) && (resultCode == -1)) {
File file = new File(getRealPathFromURI(data.getData()));
RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), getRealPathFromURI(data.getData()));
MultipartBody.Part multipartBody =MultipartBody.Part.createFormData("file",file.getName(),requestFile);
Call<ResponseBody> responseBodyCall = service.addRecord(token, userId, "fileName", multipartBody);
responseBodyCall.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
Log.d("Success", "success "+response.code());
Log.d("Success", "success "+response.message());
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Log.d("failure", "message = " + t.getMessage());
Log.d("failure", "cause = " + t.getCause());
}
});
}
}
#Multipart
#POST("myrecord")
Call<ResponseBody> addRecord(#Part("file") RequestBody file,#Part MultipartBody.Part file,
#Query("token") String token,#Query("userid") int userId,#Query("name") String name);
RequestBody requestFile =
RequestBody.create(MediaType.parse("multipart/form-data"), file);
MultipartBody.Part body =
MultipartBody.Part.createFormData("picture", file.getName(), requestFile);
String descriptionString = "your description";
RequestBody description =
RequestBody.create(
MediaType.parse("multipart/form-data"), descriptionString);
for more information look into this link:
https://futurestud.io/blog/retrofit-2-how-to-upload-files-to-server
If you would like to send file as binary in a body without using multipart you can remove #Multipart annotation from your code and use #Body annotation. It looks like
#POST("myrecord")
Call<ResponseBody> addRecord(#Query("token") String token,#Query("userid") int userId,
#Query("name") String name, #Body RequestBody file);
File file = new File(getRealPathFromURI(data.getData()));
RequestBody requestFile = RequestBody.create(MediaType.parse("image/*"), getRealPathFromURI(data.getData()));
Call<ResponseBody> responseBodyCall = service.addRecord(token, userId,
"newFileName", requestFile);
responseBodyCall.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
Log.d("Response", "="+response.code());
Log.d("Response", "= "+response.message());
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Log.d("failure", "message = " + t.getMessage());
Log.d("failure", "cause = " + t.getCause());
}
});`
public String getRealPathFromURI(Context context, Uri contentUri) {
Log.d("imin", "onClick: in image conversion");
Cursor cursor = null;
try {
String[] proj = {MediaStore.Images.Media.DATA};
cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
Log.d("imin", "onClick: in image conversion try");
return cursor.getString(column_index);
} finally {
Log.d("imin", "onClick: in image conversion finally");
if (cursor != null) {
cursor.close();
}
}
}

Categories

Resources