Retrofit2 response on file upload - android

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.

Related

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")

retrofit2 upload image to server

I can't upload image to server it send multiple request to server and server is damp
this is my code
#Multipart
#POST("userImage")
Call<ResponseBody> sendUserFeedback(#Header("SessionID") String authorization, #Part MultipartBody.Part file, #Part("uploadfile") RequestBody name);
}
selectedImageURI = data.getData();
File file = new File(selectedImageURI.getPath());
RequestBody requestBody = RequestBody.create(MediaType.parse("image/*"), file);
fileToUpload = MultipartBody.Part.createFormData("uploadfile", file.getName(), requestBody);
filename = RequestBody.create(MediaType.parse("text/plain"), file.getName());
private void executeSendFeedbackFormSendUserImage(String sessionID, MultipartBody.Part fileToUpload, RequestBody description){
UploadImage userClient = retrofit1.create(UploadImage.class);
Call<ResponseBody> call = userClient.sendUserFeedback(sessionID, fileToUpload, description);
call.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
Toast.makeText(AdminEditActivity.this,"success",Toast.LENGTH_SHORT).show();
if (response.body() != null){
response.code();
}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Toast.makeText(AdminEditActivity.this,"error:",Toast.LENGTH_SHORT).show();
}
});
}
How to fix it???

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

How to Pass the image in android using Retrofit?

Hello i am working on upload image file using retrofit.
Can any one have idea how to pass in
You need pass mulitypart object in retrofit:
MultipartBody.Part carImage = null;
if (!TextUtils.isEmpty(imagePath)) {
File file = FileUtils.getFile(getContext(), imagePath);
// create RequestBody instance from file
final RequestBody requestFile =
RequestBody.create(MediaType.parse("multipart/form-data"), file);
// MultipartBody.Part is used to send also the actual file name
carImage = MultipartBody.Part.createFormData("image", file.getName(), requestFile);
}
public static MultipartBody.Part UploadImage(String filePath,String param) {
MultipartBody.Part body = null;
try {
body = MultipartBody.Part.createFormData("", "", null);
} catch (Exception e) {
e.printStackTrace();
}
//profileUpdateRequest.setWebsite(lblWebsite.getText().toString().trim());
if ((!filePath.equals(""))) {
File file = new File(filePath);
RequestBody photo = RequestBody.create(MediaType.parse("image/*"), file);
body = MultipartBody.Part.createFormData(param, file.getName(), photo);
}
return body;
}
Step::1Pass the file Path and it will return you MultiPart body
#Multipart
#POST(Endpoint.POST_URL)
Call<DecisionStepThirdResponse> uploadUserProfile(#Part("api_id") RequestBody api_id,
#Part("api_secret") RequestBody api_secret,
#Part("api_request") RequestBody api_request,
#Part("data") RequestBody data,
#Part MultipartBody.Part profile_image);
========================
Step 2: Pass the Request like this
public void uploadUserProfile(UpdateImageRequest request, MultipartBody.Part file, Callback<UpdateImageResponse> callback) {
String api_request = "uploadUserProfile";
String data = new Gson().toJson(request);
IRoidAppHelper.Log("application_form_permission", data);
json().uploadUserProfile(
RequestBody.create(MediaType.parse("text/plain"), api_id),
RequestBody.create(MediaType.parse("text/plain"), api_secret),
RequestBody.create(MediaType.parse("text/plain"), api_request),
RequestBody.create(MediaType.parse("text/plain"), data)
, file).enqueue(callback);
}
Step 3 : And Pass the Parameter in your Serviceclass
Please go through the following link.
Have time to refer this link :)
https://medium.com/#adinugroho/upload-image-from-android-app-using-retrofit-2-ae6f922b184c#.iinz6neii
Step 1: First initialize service class
public interface ImageUploadService {
#Multipart
#POST("upload")
Call<ResponseBody> upload(
#Part("description") RequestBody description,
#Part MultipartBody.Part file
);
}
Step 2: in next step use this where you want to upload image or file
private void uploadFile(Uri fileUri) {
// create upload service client
FileUploadService service =
ServiceGenerator.createService(ImageUploadService.class);
// https://github.com/iPaulPro/aFileChooser/blob/master/aFileChooser/src/com/ipaulpro/afilechooser/utils/FileUtils.java
// use the FileUtils to get the actual file by uri
File file = FileUtils.getFile(this, fileUri);
// create RequestBody instance from file
RequestBody requestFile =
RequestBody.create(
MediaType.parse(getContentResolver().getType(fileUri)),
file
);
// MultipartBody.Part is used to send also the actual file name
MultipartBody.Part body =
MultipartBody.Part.createFormData("picture", file.getName(), requestFile);
// add another part within the multipart request
String descriptionString = "hello, this is description speaking";
RequestBody description =
RequestBody.create(
okhttp3.MultipartBody.FORM, descriptionString);
// finally, execute the request
Call<ResponseBody> call = service.upload(description, body);
call.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call,
Response<ResponseBody> response) {
Log.v("Upload", "success");
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Log.e("Upload error:", t.getMessage());
}
});
}
Step 3: you can use like this
uploadFile(Uri.fromFile(new File("/sdcard/cats.jpg")));
In your activity.
Last step: you need to add
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
In manifest in additon with
<uses-permission android:name="android.permission.INTERNET"/>
Refer this.
You can upload any type of file.
/* Create interface like below. */
public interface uploadWishImage {
#Multipart
#POST("upload/image")
Call<JsonObject> postImage(#Part MultipartBody.Part image, #Part("name") RequestBody name);
}
/* image upload code */
File file = new File("here your file path");
RequestBody reqFile = RequestBody.create(MediaType.parse("image/*"), file);
MultipartBody.Part body = MultipartBody.Part.createFormData("file", file.getName(), reqFile);
RequestBody name = RequestBody.create(MediaType.parse("text/plain"), "file");
uploadWishImage postService = RetrofitApi.makeNetworkRequestWithHeaders(AddWish.this).create(uploadWishImage.class);
Call<JsonObject> call = postService.postImage(body, name);
call.enqueue(new Callback<JsonObject>() {
#Override
public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
// somethings to do with reponse
}
#Override
public void onFailure(Call<JsonObject> call, Throwable t) {
// Log error here since request failed
}
});

Retrofit is not sending right value to server

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.

Categories

Resources