Retrofit is not sending right value to server - android

Here is code that I am using to upload image to server. But its not sending right value like user_id so that it shows me wrong result. When I hit api on chrome its working fine it gives proper result. I was using code with uploading Image is :
#Multipart
#POST("/queli_technologies/index.php/Webservice")
Call<EditProfileResponse> editProfile(#Part("u_id") String firstname,
#Part("f_name") String lastname,
#Part("l_name") String email,
#Part("c_no") String password,
#Part MultipartBody.Part file,
#Part("edit_profile") String register);
RequestBody reqFile = RequestBody.create(MediaType.parse("image/*"),file);
MultipartBody.Part body = MultipartBody.Part.createFormData("upload", file.getName(), reqFile);
service = RetroClient.getApiService();
Call<EditProfileResponse> responseCall = service.editProfile("44","Demo","android","0987654321",body,"edit_profile");
responseCall.enqueue(new Callback<EditProfileResponse>() {
#Override
public void onResponse(Call<EditProfileResponse> call, Response<EditProfileResponse> response) {
if (response.isSuccessful()){
EditProfileResponse res = response.body();
Log.e("Response " , res.getStatus() + " message : " + res.getMessage());
dialog.dismiss();
}
}
#Override
public void onFailure(Call<EditProfileResponse> call, Throwable t) {
}
});
When i donot get proper result i use this:
#Multipart
#POST("/queli_technologies/index.php/Webservice")
Call<EditProfileResponse> editProfile(#Part("u_id") RequestBody userId,
#Part("f_name") RequestBody frstname,
#Part("l_name") RequestBody lastname,
#Part("c_no") RequestBody contctnum,
#Part MultipartBody.Part file,
#Part("edit_profile") RequestBody edit);
File file = new File(BaseActivity.basicImagePath);
RequestBody reqFile = RequestBody.create(MediaType.parse("image/*"), file);
MultipartBody.Part body = MultipartBody.Part.createFormData("upload", file.getName(), reqFile);
service = RetroClient.getApiService();
String text = "31";
RequestBody useridbody =RequestBody.create(MediaType.parse("text/plain"), text);
RequestBody fnbody =RequestBody.create(MediaType.parse("text/plain"), "Demo");
RequestBody lnbody =RequestBody.create(MediaType.parse("text/plain"), "android");
RequestBody conbody =RequestBody.create(MediaType.parse("text/plain"), "0987654321");
RequestBody isbody =RequestBody.create(MediaType.parse("text/plain"), "edit_profile");
Call<EditProfileResponse> responseCall = service.editProfile(useridbody,fnbody,lnbody,conbody,body,isbody);
responseCall.enqueue(new Callback<EditProfileResponse>() {
#Override
public void onResponse(Call<EditProfileResponse> call, Response<EditProfileResponse> response) {
if (response.isSuccessful()){
EditProfileResponse res = response.body();
Log.e("Response " , res.getStatus() + " message : " + res.getMessage());
dialog.dismiss();
}
}
#Override
public void onFailure(Call<EditProfileResponse> call, Throwable t) {
Log.e("Failure Response " , t +"");
}
});
Still Im not able get right result. Api response in Log gives {"status":"0","message":"User doesnot exist"} when using through retrofit. and from
server it shows {"status":"1","message":"User profile Updated"}
Is this retrofit issue or my coding issue?

Move the file to last.
#POST("/queli_technologies/index.php/Webservice")
Call<EditProfileResponse> editProfile(#Part("u_id") String firstname,
#Part("f_name") String lastname,
#Part("l_name") String email,
#Part("c_no") String password,
#Part("edit_profile") String register,
#Part MultipartBody.Part file);
I think, it should work.

Related

How to pass parameters for image as file and name using retrofit in android

Hi in the below code below code is my php code.I want to send file from my client .client to sending file as well as filename.I want to sent all the parameters from android app and send to the server.below php code from server based on server I am sending from the client but it is not working
Can any one help me where I did the mistake
example.php:
$data = array(
'_session'=>$session,
'file' => $file,
'_operation' => 'saveRecord',
'module' => $module,
'sourceModule' => 'Potentials',
'sourceRecord' => '13x37913',
'values' => json_encode(array('notes_title'=>'test','filename' => $_FILES['file']['name'],'assigned_user_id'=>1,"filelocationtype"=>"I", "filestatus"=>1))
);
below is my api with the following parameters as below
Api.java:
#POST("api.php")
#Multipart
Call<SaveContactModule> SaveDocuments(#Part MultipartBody.Part operation,
#Part MultipartBody.Part session,
#Part MultipartBody.Part module,
#Part MultipartBody.Part sourceRecord,
#Part MultipartBody.Part values,
#Part MultipartBody.Part sourceModule,
#Part MultipartBody.Part file);
below activity I am sending to the server but somewhere I did the misatke.
MainActivity.java:
private void saveclosedwon() {
handler.postDelayed(new Runnable() {
#Override
public void run() {
progressDialog = new ProgressDialog(getActivity());
progressDialog.setIndeterminate(true);
progressDialog.setMessage("Loading...");
progressDialog.setCanceledOnTouchOutside(false);
progressDialog.setCancelable(false);
progressDialog.show();
sessionId = getActivity().getIntent().getStringExtra("sessionId");
String operation = "saveRecord";
sourceRecord = "13x53090";
String module = "Documents";
String sourceModule = "Potentials";
// RequestBody requestFile = RequestBody.create(MediaType.parse(getContext().getContentResolver().getType(filePath)), mPhotoFile);
JSONObject postdata = new JSONObject();
MultipartBody.Part body = MultipartBody.Part.createFormData("file", filename, requestFile);
try {
postdata.put("notes_title", notes_title);
postdata.put("filename", filename);
postdata.put("assigned_user_id", ids);
postdata.put("filelocationtype", "I");
postdata.put("filestatus", "1");
} catch (JSONException e) {
e.printStackTrace();
}
//String values= postdata.getString(firstname,lastname,jobtile,contacttype,speclization,mobiles,email);
final GetNoticeDataService service = RetrofitInstance.getRetrofitInstance().create(GetNoticeDataService.class);
MultipartBody.Part session = MultipartBody.Part.createFormData("_session",sessionId);
MultipartBody.Part operation_won = MultipartBody.Part.createFormData("operation",operation);
MultipartBody.Part module_won = MultipartBody.Part.createFormData("module",module);
MultipartBody.Part sourceRecord_won = MultipartBody.Part.createFormData("sourceRecord",sourceRecord);
MultipartBody.Part sourceModule_won = MultipartBody.Part.createFormData("sourceModule",sourceModule);
MultipartBody.Part sourceModule_postdata = MultipartBody.Part.createFormData("values",postdata.toString());
MultipartBody.Part file = MultipartBody.Part.createFormData("file", "file");
/** Call the method with parameter in the interface to get the notice data*/
Call<SaveContactModule> call = service.SaveDocuments(operation_won, session, module_won, sourceRecord_won, sourceModule_postdata, sourceModule_won,body);
/**Log the URL called*/
Log.i("URL Called", call.request().url() + "");
call.enqueue(new Callback<SaveContactModule>() {
#Override
public void onResponse(Call<SaveContactModule> call, Response<SaveContactModule> response) {
Log.e("response", new Gson().toJson(response.body()));
if (response.isSuccessful()) {
Log.e("response", new Gson().toJson(response.body()));
SaveContactModule saveContactModule = response.body();
String success = saveContactModule.getSuccess();
if (success.equals("true")) {
progressDialog.dismiss();
Toast.makeText(getContext(), "Successfully saved", Toast.LENGTH_LONG).show();
fragment = new SalesStageFragment();
loadFragment(fragment);
} else {
progressDialog.dismiss();
Toast.makeText(getContext(), "Invalid details", Toast.LENGTH_LONG).show();
}
}
progressDialog.dismiss();
}
#Override
public void onFailure(Call<SaveContactModule> call, Throwable t) {
Log.d("error", t.getMessage());
progressDialog.dismiss();
}
});
}
}, 0);
return;
}
As you implemented both multipart and formurlencoded. As per your error it is said that either you should use #Multpart or #FormUrlEncoded but not both at once in the api call. i.e,
#FormUrlEncoded
Call<SaveContactModule> SaveDocuments(#Field("_operation") String operation,
#Field("_session") String session,
#Field("module") String module,
#Field("sourceRecord") String sourceRecord,
#Field("values") JSONObject values,
#Field("sourceModule") String sourceModule,
#Part RequestBody file,
#Part("file") Uri image);
or,
#Multipart
Call<SaveContactModule> SaveDocuments(#Part MultipartBody.Part String operation,
#Part MultipartBody.Part session,
#Part MultipartBody.Part module,
#Part MultipartBody.Part sourceRecord,
#Part MultipartBody.Part values,
#Part MultipartBody.Part sourceModule,
#Part MultipartBody.Part file,
#Part MultipartBody.Part image);
but not both annotations at once.

Retrofit multipart array key but single value only

My target or my goal is to have a request like this so that it will succeed:
Now my current code looks like this:
WebApi client = ServiceGenerator.createService(WebApi.class);
final Call<BaseResponse<BookingInfoEntity>> call = client.startBooking(
WebUtilities.createPartFromString(SharePreferences.getUserId(context)),
WebUtilities.createPartFromString(""), //trainer_id
WebUtilities.createPartFromString(String.valueOf(listener.getTrainerTypesObject().get(0))), //train type
WebUtilities.createPartFromString(String.valueOf(hours)),
WebUtilities.createPartFromString(String.valueOf(payment_id)),
WebUtilities.createPartFromString(SharePreferences.getCityId(context)),
WebUtilities.createPartFromString(listener.getSelectedDate()));
}
public static RequestBody createPartFromString(String descriptionString) {
return RequestBody.create(okhttp3.MultipartBody.FORM, descriptionString);
}
#Multipart
#POST(START_BOOKING)
Call<BaseResponse<BookingInfoEntity>> startBooking(#Part("trainee_id") RequestBody trainee_id,
#Part("trainer_id") RequestBody trainer_id,
#Part("trainer_types[][trainer_type_id]")RequestBody train_type,
#Part("number_of_hours") RequestBody number_of_hours,
#Part("payment_type_id") RequestBody payment_type_id,
#Part("city_id") RequestBody city_id,
#Part("meeting_date") RequestBody meeting_date);
My problem is: How can i dynamically insert
trainer_types[][trainer_type_id],
like i want when i have 5 trainer type id,
how can i insert a 5 trainer_type_id in they key and set a value with it?
I just want to replicate the image above so that i can properly solve this value.
Your request should be like this:
#Multipart
#POST(START_BOOKING)
Call<BaseResponse<BookingInfoEntity>> startBooking(#Part("trainee_id") RequestBody trainee_id,
#Part("trainer_id") RequestBody trainer_id,
#Part List<MultipartBody.Part> train_type,
#Part("number_of_hours") RequestBody number_of_hours,
#Part("payment_type_id") RequestBody payment_type_id,
#Part("city_id") RequestBody city_id,
#Part("meeting_date") RequestBody meeting_date);
Create List of trainer_types for file types
#NonNull
private MultipartBody.Part prepareFilePart(String partName, Uri fileUri, String file_type) {
File file;
if (file_type.contains("video")) {
file = new File(fileUri.getPath());
} else {
file = FileUtils.getFile(this, fileUri);
}
RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
// MultipartBody.Part is used to send also the actual file name
return MultipartBody.Part.createFormData(partName, file.getName().replaceAll(" ", "%20"), requestFile);
}
Call API with multiple Same keys dientional arrays
private void startUploadingList(ArrayList<String> selectedItems1) {
List<MultipartBody.Part> parts = new ArrayList<>();
try {
for (int i = 0; i < selectedItems1.size(); i++) {
if (selectedItems1.get(i) != null) {
parts.add(prepareFilePart("trainer_types[][" + i + "]", Uri.parse(selectedItems1.get(i)), "image/png"));
}
}
RequestBody description = RequestBody.create(MediaType.parse("multipart/form-data"), "Your Value");
// add another part within the multipart request
// finally, execute the request
Call<BaseResponse<BookingInfoEntity>> call = APIClient.getInterface().startBooking(description ,description ,parts, description,description ,description ,description );
call.enqueue(new Callback<BaseResponse<BookingInfoEntity>>() {
#Override
public void onResponse(Call<BaseResponse<BookingInfoEntity>> call, Response<BaseResponse<BookingInfoEntity>> response) {
Log.e("Upload", "success");
}
#Override
public void onFailure(Call<BaseResponse<BookingInfoEntity>> call, Throwable t) {
call.cancel();
Log.e("Upload error:", t.getMessage());
t.printStackTrace();
}
});
} catch (Exception e) {
e.printStackTrace();
}
}

Found error 'Response{protocol=http/1.1, code=404, message=Not Found, url=url}' when sending file through retrofit2

I am facing problem when sending file through retrofit2. But the web api working fine on Postman hit. Error Stated in responsebody:
Response{protocol=http/1.1, code=404, message=Not Found, url=MYURL}
Retrofit2 endpoint:
#Multipart
#POST("FileStorage/UploadDataFile")
Call<ResponseBody> uploadFile(#Part MultipartBody.Part file,#Part("file") RequestBody name);
Updated code:
// Uploading File
private void uploadFile() {
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) +
File.separator + "dbBackup"+
File.separator +"gps_db_4522_190122114644.sqlite");
//File file = new File(mediaPath);
Retrofit retrofit = RetrofitSingleton.getInstance(getActivity().getBaseContext());
final CommonApiInterface commonApiInterface = retrofit.create(CommonApiInterface.class);
RequestBody requestBody = RequestBody.create(MediaType.parse("*/*"), file);
MultipartBody.Part fileToUpload = MultipartBody.Part.createFormData("file", file.getName(), requestBody);
RequestBody filename = RequestBody.create(MediaType.parse("text/plain"), file.getName());
commonApiInterface.uploadFile(fileToUpload,filename).enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if(response.isSuccessful()) {
Toast.makeText(getActivity(), "Saved Successfully...", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Toast.makeText(getActivity(), "Save Fail: " + t, Toast.LENGTH_SHORT).show();
}
});
}
Finally i found my problem. The endpoint was incorrect
#Multipart
#POST("FileStorage/UploadDataFile")
Call<ResponseBody> uploadFile(#Part MultipartBody.Part file,#Part("file") RequestBody name);
correct endpoint is #POST("FileProcessing/UploadDataFile")

How to upload image through retrofit?

I have looked through many stackoverflow answers but could not upload image. It used to give me Internal Server Error. Now I found a solution but it sends a null image to the server. Could you please show me where I am doing wrong.
Here is my Request CODE:
#Multipart
#POST("lostandfound")
Call<ResponseBody> uploadLostAndFound(#PartMap Map<String, RequestBody> map);
And my CALL:
Map<String, RequestBody> map = new HashMap<>();
map.put("usermail", toRequestBody("mohammad_sed"));
map.put("content", toRequestBody(content));
map.put("islost", toRequestBody(String.valueOf(isLost)));
map.put("wasfound", toRequestBody(foundPlace));
map.put("tofind", toRequestBody(toFindPlace));
File file = new File(destination);
RequestBody reqFile = RequestBody.create(MediaType.parse("image"), file);
MultipartBody.Part body = MultipartBody.Part.createFormData("upload", file.getName(), reqFile);
map.put("img", body);
ForumService client = Utils.getBuilder().create(ForumService.class);
Call<ResponseBody> call = client.uploadLostAndFound(map);
call.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if (response.isSuccessful()) {
mProgressDialog.dismiss();
// Toast.makeText(getApplicationContext(), "Request created", Toast.LENGTH_SHORT).show();
} else {
mProgressDialog.dismiss();
}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
mProgressDialog.dismiss();
Toast.makeText(getApplicationContext(), "Failed to upload!", Toast.LENGTH_SHORT).show();
}
});
// This method converts String to RequestBody
public static RequestBody toRequestBody(String value) {
RequestBody body = RequestBody.create(MediaType.parse("text/plain"), value);
return body;
}
I tried:
#Multipart
#POST("lostandfound")
Call<ResponseBody> uploadLostAndFound(#Part MultipartBody.Part photo,
#PartMap Map<String, RequestBody> map);
But this way I get Internal server error.
Thanks in advance.
I found the solution. I tried from postman and it was working fine.
The solution is that I had to use:
#Multipart
#POST("lostandfound")
Call<ResponseBody> uploadLostAndFound(#Part MultipartBody.Part photo,
#PartMap Map<String, RequestBody> map);
and:
RequestBody reqFile = RequestBody.create(MediaType.parse("image/*"), file);
MultipartBody.Part body = MultipartBody.Part.createFormData("img", file.getName(), reqFile);
The change is I had to use "img" instead of "upload". That is a stupid mistake :D

Retrofit2 response on file upload

I want to upload zip file on myserver. I am using Retrofit2. I have used the following code.
private void uploadFile() {
// create upload service client
FileUploadService service =
ServiceGenerator.createService(FileUploadService.class);
File file = uploadFile;
RequestBody requestFile =
RequestBody.create(
MediaType.parse("application/x-www-form-‌urlencoded"),
file
);
MultipartBody.Part body =
MultipartBody.Part.createFormData("fileUpload", file.getName(), requestFile);
String descriptionString = "hello, this is description speaking";
RequestBody description =
RequestBody.create(
okhttp3.MultipartBody.FORM, descriptionString);
Call<JSONObject> call = service.upload(description, body);
call.enqueue(new Callback<JSONObject>() {
#Override
public void onResponse(Call<JSONObject> call,
Response<JSONObject> response) {
System.out.println("UploadFragment.onResponse " + response);
Log.v("Upload", "success");
}
#Override
public void onFailure(Call<JSONObject> call, Throwable t) {
Log.d("Upload error:", t.getCause().toString());
}
});
}
My upload service is like.
public interface FileUploadService {
#Multipart
#POST("myurl")
Call<JSONObject> upload(
#Part("description") RequestBody description,
#Part MultipartBody.Part file
);
}
Problem When I upload file I get response {protocol=http/1.1, code=200, message=OK, url=http://myUrl.
It is not the response returned by my server. How can get my server response?
Its retrofit response. You will get your response in body.
response.body().toString();
Use this
System.out.println("UploadFragment.onResponse " + response.body().toString());
I hope this will help you.

Categories

Resources