PUT request method not working retrofit 2 android - android

All request method is working fine, but PUT request method is never successful. Its working perfectly in 'Postman' with same parameters. My request calling interface
#Multipart
#PUT("api/v1/user/{id}/")
Call<UpdateProfileResponse> updateUserProfile(
#Header("Authorization") String token,
#Path("id") int user_id,
#Part("name") RequestBody name,
#Part("email") RequestBody email,
#Part("password") RequestBody password,
#Part MultipartBody.Part picture,
#Part("city") RequestBody city,
#Part("country") RequestBody country,
#Part("bank_name") RequestBody bank_name,
#Part("bank_account_name") RequestBody bank_account_name,
#Part("bank_account_number") RequestBody bank_account_number,
#Part("user_type") RequestBody user_type,
#Part("address") RequestBody address
);
Request calling (enqueuing)
mApiClient.updateUserProfile(access_token, user_id, name, email, password, bodyPicture, city,
country, bank_name, bank_account_name, bank_account_number, user_type, address)
.enqueue(new Callback<UpdateProfileResponse>() {
#Override
public void onResponse(Call<UpdateProfileResponse> call, Response<UpdateProfileResponse> response) {
if (response.isSuccessful()) {
Log.d(TAG, "update response: " + response.body().toString());
} else {
Log.d(TAG, "update response: " + response.errorBody());
}
}
#Override
public void onFailure(Call<UpdateProfileResponse> call, Throwable t) {
t.printStackTrace();
}
});
its always finishes in OnResponse else block (not successful). Not getting any clue what I am doing wrong. Need suggestion to fix this.

Related

Android Image Uploading on Localhost but not on online server

I am building a Laravel-based API. In the project, I want to upload image using post method to the API server
the image file is uploading on localhost database but when I try to upload the image on online server which is namecheap there image error code is 405.
I wasted 2 days but I don't now what is the error.
Please anyone can help me.
Thanks in advance
Here is android code
#Multipart
#POST("update-client")
Call<CustomerModel> update_user(#Part("id") RequestBody id,
#Part("name") RequestBody name, #Part("address") RequestBody address,
#Part("user_op_phone") RequestBody city,
#Part MultipartBody.Part file,
#Part("avatar") RequestBody image);
public void update_user_info(String name,String address,String no){
progressDialog.show();
RequestBody requestFile = null;
MultipartBody.Part body = null;
if(file!=null && file.length()>0) {
requestFile =
RequestBody.create(MediaType.parse("multipart/form-data"), file);
// MultipartBody.Part is used to send also the actual file name
body =
MultipartBody.Part.createFormData("avatar", file.getName(), requestFile);
}
RequestBody p_id = RequestBody.create(MediaType.parse("text/plain"),appSessionManager.getUserId());
RequestBody p_name = RequestBody.create(MediaType.parse("text/plain"),name);
RequestBody p_address = RequestBody.create(MediaType.parse("text/plain"),address);
RequestBody p_no = RequestBody.create(MediaType.parse("text/plain"),no);
Call<CustomerModel> call1 = apiPHP.update_user(body,requestFile);
call1.enqueue(new Callback<CustomerModel>() {
#Override
public void onResponse(Call<CustomerModel> call, Response<CustomerModel> response) {
progressDialog.dismiss();
// VendorModel user1 = response.body();
if(response.errorBody()==null){
// if(response.code()==201) {
Toast.makeText(getApplicationContext(), response.body().message, Toast.LENGTH_LONG).show();
// }
}
}
#Override
public void onFailure(Call<CustomerModel> call, Throwable t) {
Toast.makeText(getApplicationContext(),t.getMessage() , Toast.LENGTH_SHORT).show();
call.cancel();
}
});
}
Laravel Api routes is
Route::post("update-client", "Client\ClientController#updateClient");

Why automatic Atteched "\\" in String Using POST method with Params in Retrofit?

Hello i using Post method in retrofit . I have one Activity ProfileActivity and I try to update ProfileActivity. When i try to update my Activity it response like :-
"name": "\"\\\"\\\\\\\"\\\\\\\\\\\\\\\"JohndoeOperator\\\\\\\\\\\\\\\"\\\\\\\"\\\"\"",
I try to remove this extra "\"\" from my String ,But question is why
this add when i try to update my profile
Here is my code:-
APIInterface.java
#Multipart
#POST("updateProfile")
Call<UpdateProfileUserSideResponse> updateProfile(#Part("userId") int userId,
#Part("name") String name,
#Part("companyName") String companyName,
#Part("gstin") String gstin,
#Part("address") String address,
#Part("landmark") String landmark,
#Part("city") String city,
#Part("state") String state,
#Part("pincode") String pincode,
#Part MultipartBody.Part image);
and Here is my API call :-
final ApiInterface api = ApiClient.getApiService();
Call<UpdateProfileUserSideResponse> call = api.updateProfile(preferenceManager.getUserId(), edt_user_FullName.getText().toString(), "", "", edt_user_address.getText().toString(), edt_user_landMark.getText().toString(), edt_user_city.getText().toString(), edt_user_state.getText().toString(), edt_user_pincode.getText().toString(), fileToUpload);
call.enqueue(new Callback<UpdateProfileUserSideResponse>() {
#Override
public void onResponse(Call<UpdateProfileUserSideResponse> call, Response<UpdateProfileUserSideResponse> response) {
Toast.makeText(getContext(), "" + response.message(), Toast.LENGTH_SHORT).show();
preferenceManager.setName(response.body().getData().getName());
Log.e("AHHHHHHAHAAA", "" + response.body().getData().getName());
preferenceManager.setAddress(response.body().getData().getAddress());
preferenceManager.setLandmark(response.body().getData().getLandmark());
preferenceManager.setCity(response.body().getData().getCity());
preferenceManager.setState(response.body().getData().getState());
preferenceManager.setPincode(response.body().getData().getPincode());
preferenceManager.setImage(response.body().getData().getImage());
progressDialog.dismiss();
}
#Override
public void onFailure(Call<UpdateProfileUserSideResponse> call, Throwable t) {
Toast.makeText(getContext(), t.getMessage(), Toast.LENGTH_LONG).show();
progressDialog.dismiss();
}
});
First, check your API on postman plugin of chrome browser
Is gives the same result on postman as well.

Upload files using retrofit2 - file was being uploaded but on "onFailure" response

I need to upload an image as a file, already tried different solutions from the stack but I still stuck. Anyone can explain to me what I am doing wrong?
UPLOAD FUNCTION
private void EnviarFotos(){
iGeoPBService geoPBService = GeoPBService.getInstance().usarServico();
List<Foto> listaFotos = bancoDadosController.syncFotos();
for (final Foto foto : listaFotos){
String numObra = foto.getNumeroObra();
String idAcomp = foto.getIdAcompanhamento();
String idMedicao = foto.getIdMedicao();
String imagem = foto.getImagem();
final File file = FileFoto(imagem);
RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"),file);
MultipartBody.Part multipartBody = MultipartBody.Part.createFormData("file",foto.getNomeFoto(),requestFile);
if (idAcomp.equals("N/A")){
Call<String> envioMed = geoPBService.uploadFotoMedicao(idJurisdicionado,numObra,idMedicao,multipartBody);
envioMed.enqueue(new Callback<String>() {
#Override
public void onResponse(Call<String> call, Response<String> response) {
if (response.isSuccessful()){
bancoDadosController.atualizaStatusSyncFoto(foto.getNomeFoto());
AttInfos();
Log.d("TESTE","FOTO ENVIADA COM SUCESSO!!!");
file.delete();
}else {
Log.d("TESTE","msg :"+ response.message());
Log.d("TESTE","errorBody :"+ response.errorBody().toString());
Toast.makeText(getBaseContext(),response.message(),Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<String> call, Throwable t) {
Log.d("TESTE","DEU MERDA!!!");
Log.d("TESTE","throw :"+ t.getMessage());
Log.d("TESTE","cause :"+ t.getCause());
Log.d("TESTE","lmsg :"+ t.getLocalizedMessage());
Log.d("TESTE","Stack :"+ t.getStackTrace().toString());
Toast.makeText(getBaseContext(),t.getMessage(),Toast.LENGTH_SHORT).show();
}
});
}else {
Call<String> envioAcomp = geoPBService.uploadFotoAcompanhamento(idJurisdicionado,numObra,idAcomp,multipartBody);
envioAcomp.enqueue(new Callback<String>() {
#Override
public void onResponse(Call<String> call, Response<String> response) {
AttInfos();
Log.d("TESTE","FOTO ENVIADA COM SUCESSO!!!");
file.delete();
}
#Override
public void onFailure(Call<String> call, Throwable t) {
Log.d("TESTE","DEU MERDA!!!");
Toast.makeText(getBaseContext(),t.getMessage(),Toast.LENGTH_SHORT).show();
}
});
}
}
}
INTERFACE
public interface iGeoPBService {
#Multipart
#POST("obras/uploadFotoMedicao/{jurisdicionado}/{numObra}/{idMedicao}")
Call<String> uploadFotoMedicao(#Path("jurisdicionado") String idJurisdicionado,#Path("numObra")String numObra,#Path("idMedicao") String idMedicao, #Part MultipartBody.Part file);
#Multipart
#POST("obras/uploadFotoAcompanhamento/{jurisdicionado}/{numObra}/{idAcompanhamento}")
Call<String> uploadFotoAcompanhamento(#Path("jurisdicionado") String idJurisdicionado, #Path("numObra")String numObra, #Path("idAcompanhamento") String idAcompanhamento, #Part MultipartBody.Part file);
}
My code already has some changes based on other answers a similar question about upload files with retrofit2 but after executing my code always fall on "onFailure"
Logcat show this:
07-13 14:14:44.035 8937-8937/despesalegal.tce.pb.gov.br.despesalegal D/TESTE:
throw :Expected value at line 1 column 1 path $
07-13 14:14:44.035 8937-8937/despesalegal.tce.pb.gov.br.despesalegal D/TESTE:
cause :null
07-13 14:14:44.035 8937-8937/despesalegal.tce.pb.gov.br.despesalegal D/TESTE:
localized msg :Expected value at line 1 column 1 path $
07-13 14:14:44.035 8937-8937/despesalegal.tce.pb.gov.br.despesalegal D/TESTE:
Stacktrace :[Ljava.lang.StackTraceElement;#b4b765b
My file was being uploaded to the server but on retrofit "onFailure" response method
What I'm doing wrong? Actually, the problem can be on the server side?
[EDIT]
I changed some things on my code and now I'm getting the "onResponse" correctly.
SERVICE CLASS
private void buildRetrofit(String baseUrl) {
*OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder();
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(HttpLoggingInterceptor.Level.BASIC);
clientBuilder.addInterceptor(logging);
clientBuilder.retryOnConnectionFailure(false);
clientBuilder.followRedirects(true);
OkHttpClient client = clientBuilder.retryOnConnectionFailure(true).build();*
*Gson gson = new GsonBuilder()
.setLenient()
.create();*
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(baseUrl)
*.client(client)*
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
this.requestsGeo = retrofit.create(iGeoPBService.class);
}
INTERFACE
#Multipart
#POST("obras/uploadFotoMedicao/{jurisdicionado}/{numObra}/{idMedicao}")
Call<ResponseBody> uploadFotoMedicao(#Path("jurisdicionado") String idJurisdicionado, #Path("numObra")String numObra, #Path("idMedicao") String idMedicao, #Part MultipartBody.Part file, #Part("name") RequestBody name);
#Multipart
#POST("obras/uploadFotoAcompanhamento/{jurisdicionado}/{numObra}/{idAcompanhamento}")
Call<ResponseBody> uploadFotoAcompanhamento(#Path("jurisdicionado") String idJurisdicionado, #Path("numObra")String numObra, #Path("idAcompanhamento") String idAcompanhamento,#Part MultipartBody.Part body,#Part("name") RequestBody name);
Just change your RequestBody to this:
RequestBody requestFile = RequestBody.create(MediaType.parse("image/*"), file);
Your MediaType sent were wrong...

Retrofit - throwing an exception java.lang.IllegalArgumentException: Only one encoding annotation is allowed

Hello guys here is my sample code
#FormUrlEncoded
#Multipart
#POST("registration.php")
Call<Signup> getSignupResponse(#Field("email") String email,
#Field("lname") String lname,
#Field("fname") String fname,
#Field("password") String password,
#Part("filename") File file);
Issue is when i am trying to add File Parameter as a Part its throwing me a error other wise if i use only #Field it works great but not working after i add #Part in it
- is there a no way to use #Field and #part together in Retrofit??
- If yes than tell a reason, If no tell me a proper way
I will appreciate your answer and thank you in advance
Note : Tell me a suggestions in comments before you vote.
You cannot use both #FormUrlEncoded and #Multipart on a single method.
An HTTP request can only have one Content-Type and both of those are
content types.
#FormUrlEncoded (for android) | application/x-www-form-urlencoded(for web)
#Multipart (for android) | multipart/form-data(for web)
use like this .....
#Multipart
#POST("photos/upload")
Call<Result> upload(#Part("Token") RequestBody token, #Part("Photo_Type") RequestBody type, #Part MultipartBody.Part file );
and in call like this .....
String token="your string";
File file = new File(path);
RequestBody tokenRequest = RequestBody.create(MediaType.parse("text/plain"), token);
RequestBody type = RequestBody.create(MediaType.parse("text/plain"), true + "");
MultipartBody.Part filePart = MultipartBody.Part.createFormData("file", file.getName(), RequestBody.create(MediaType.parse("image/*"), file));
Call<Result> call = qikGrubApi.upload(tokenRequest, type, filePart);
call.enqueue(new Callback<Result>() {
#Override
public void onResponse(Call<Result> call, Response<Result> response) {
progress.dismiss();
if (response.isSuccessful()) {
if (response.body().getSuccess()) {
nextPage(response.body().getMessage());
} else
Toast.makeText(UploadActivity.this, response.body().getMessage(), Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(UploadActivity.this, "Sorry for inconvince server is down", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<Result> call, Throwable t) {
progress.dismiss();
Toast.makeText(UploadActivity.this, "Check your Internet connection", Toast.LENGTH_SHORT).show();
}
});
}
Note:- Use above example for your File POST and let me know , if you stuck anywhere.
For more Detail info click this
EDIT:-
For your case use like this .....
#Multipart
#POST("registration.php")
Call<Signup> getSignupResponse(#Part("email") RequestBody email,
#Part("lname") RequestBody lname,
#Part("fname") RequestBody fname,
#Part("password") RequestBody password,
#Part MultipartBody.Part filename);
and use retrofit call like this .....
File file = new File(path);
RequestBody emailRequest = RequestBody.create(MediaType.parse("text/plain"), email);
RequestBody lnameRequest = RequestBody.create(MediaType.parse("text/plain"), lname);
RequestBody fnameRequest = RequestBody.create(MediaType.parse("text/plain"), fname);
RequestBody passwordRequest = RequestBody.create(MediaType.parse("text/plain"), password);
MultipartBody.Part filePart = MultipartBody.Part.createFormData("file", file.getName(), RequestBody.create(MediaType.parse("image/*"), file));
Call<Signup> call = qikGrubApi.upload(emailRequest, lnameRequest ,fnameRequest , passwordRequest, filePart);
call.enqueue(new Callback<Signup>() {
#Override
public void onResponse(Call<Signup> call, Response<Signup> response) {
progress.dismiss();
if (response.isSuccessful()) {
if (response.body().getSuccess()) {
nextPage(response.body().getMessage());
} else
Toast.makeText(UploadActivity.this, response.body().getMessage(), Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(UploadActivity.this, "Sorry for inconvince server is down", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<Signup> call, Throwable t) {
progress.dismiss();
Toast.makeText(UploadActivity.this, "Check your Internet connection", Toast.LENGTH_SHORT).show();
}
});
}
Example

Retrofit 2 multipart file upload with different file names

This is my code. It properly works. But I want to upload other image types like png, jpeg ,etc. Therefore I want to change filename=\"file1.jpeg"
Also I want to send different number of files at the same time.
Please help me to resolve this. Thank you.
public interface FileUploadService {
#Multipart
#POST("upload")
Call<ResponseBody> upload(#Part("description") RequestBody description,#Part("file1\"; filename=\"file1.jpeg") RequestBody file1);
}
private void uploadFile() {
FileUploadService service =
ServiceGenerator.createService(FileUploadService.class);
RequestBody requestFile =
RequestBody.create(MediaType.parse("multipart/form-data"), new File("/path/to/mypic.jpeg"));
String descriptionString = "hello, this is description speaking";
RequestBody description =
RequestBody.create(
MediaType.parse("multipart/form-data"), descriptionString);
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());
}
});
}
Try this one:
#POST("upload")
fun upload(#BODY parts: MultipartBody): Call<ResponseBody>
and the client side would look like this:
val parts = MultipartBody.Builder()
.addFormDataPart(name = "name",filename = "yourDynamicFileName", RequestBody.create(...))
.build()
// don't forget to name an extension of your file
api.upload(parts).execute()

Categories

Resources