//url to consume - baseURL/xyz/test-map.php?key=3ec9864e9db5fb47da338d108503d4612fc65b80
#FormUrlEncoded
#POST("xyz/test-map.php")
Call<Root> getResponseForApi (#Field(value = "key", encoded = true) String key ,
#Field("auth_key") int auth_key,
#Field("password") int password) ;
when i try to call ,
Call<Root> call = apiServiceImplementation.getResponseForApi(key, auth_key, password);
call.enqueue(new Callback<Root>() {
#Override
public void onResponse(Call<Root> call, Response<Root> response) {
Root data = response.body();
}
#Override
public void onFailure(Call<Root> call, Throwable t) {
Log.e("TAG", "onFailure: " );
}
});
i am getting URL in on response as without query parameter like "baseURL/xyz/test-map.php" only.
why it is not encoding
you can use both #Query and #Field in your request.
here is your solution.
#FormUrlEncoded
#POST("xyz/test-map.php")
Call<Root> getResponseForApi (#Query("key") String key ,
#Field("auth_key") int auth_key,
#Field("password") int password) ;
Related
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.
I'm using retrofit2 for password recovery, an API request is sent to the server with an email address which is entered by the user.
I'm only setting the email in the POJO ,and after the conversion, the JSON string looks like this:
{"email":"email#email.com", "password":"", "password_confirmation":"", "token":""}
But the JSON I need to send out, should look like this:
{"email":"email#email.com"}
If I'll create another POJO class with an email param then I'll get the required string, but I just want to know if it is possible, using the current POJO.
How would one convert a POJO object to a JSON string using gson for a specified field?
Please Refer to the below code:
public class User {
private String email;
private String password;
private String password_confirmation;
private String token;
public User() {
this.email="";
this.password="";
this.password_confirmation="";
this.token="";
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getPassword_confirmation() {
return password_confirmation;
}
public void setPassword_confirmation(String password_confirmation) {
this.password_confirmation = password_confirmation;
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
}
My Api interface
public interface Api{
#POST("/api/password/create")
#Headers({"Accept:application/json", "Content-Type:application/json"})
Call<User> Create(#Body RequestBody requestBody);
}
My Retrofit method
private void authenticateEmail(final Context context) {
User user=new User();
Api api=new Api();
String email = edt_forgot_email.getText().toString().trim();
Gson gson = new GsonBuilder()
.setDateFormat(SERVICE_DATE_FORMAT)
.setLenient()
.create();
api = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
user.setEmail(email);
Gson lGson = new GsonBuilder().setDateFormat(SERVICE_DATE_FORMAT).create();
String jsonString = lGson.toJson(user);
Log.d("debug", "jsonString==>" + jsonString);
final RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), jsonString);
Call<User> call = api.Create(requestBody);
Log.d("debug", "url: " + call.request().url().toString());
call.enqueue(new Callback<User>() {
#Override
public void onResponse(#NonNull Call<User> call, #NonNull Response<User> response) {
Log.d("debug", "responsecode==>" + response.code());
Log.d("debug", "responsebody==>" + response.body());
if (response.code() == 200) {
String msg = "We have emailed you OTP";
Toast.makeText(activity, msg, Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(#NonNull Call<User> call, #NonNull Throwable t) {
Toast.makeText(activity, "server error",Toast.LENGTH_SHORT).show();
}
});
}
Remove this code from constructor :
public User() {
this.email="";
this.password="";
this.password_confirmation="";
this.token="";
}
If you want to exclude empty values from output json, you should make it as null.
Good luck!
You can just create a JSON Object for the single field like this:
JSONObject data =new JSONObject();
data.put("email", email#email.com)
send data object to the retrofit.
I have a url like this
http://182.72.198.001:8080/MyLogin/login/xxxxxx/yyyyyy
userName : xxxxxx
password : yyyyyy
I am using retrofit to get the above url response but it returning null my retrofit class is
public class ApiClient {
public static Retrofit retrofit = null;
public static Retrofit getApiCLient() {
if (retrofit == null) {
retrofit = new Retrofit.Builder().baseUrl("http://182.72.198.001:8080/MyLogin/").addConverterFactory
(GsonConverterFactory.create()).build();
}
return retrofit;
}
}
and myInterface class is
public interface MyInterface {
#GET("login/")
Call<ResponseBody> LoginValidation(#Query("userName") String username, #Query("password") String password);
}
My main class is
MyInterface loginInterface;
loginInterface = ApiClient.getApiCLient().create(MyInterface.class);
private void LoginUser()
{
final String usedrname = username1.getText().toString();
final String password = password1.getText().toString();
Call<ResponseBody> call = loginInterface.LoginValidation(usedrname,password);
Log.i("Tag","Interface" + usedrname+password);
call.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
Log.i("Tag","Respose" + response.body()); // this body returns null
Toast.makeText(getApplicationContext(), "Thank You!", Toast.LENGTH_SHORT).show();
editor.putString("username",usedrname);
editor.putString("password",password);
editor.putBoolean("isLoginKey",true);
editor.commit();
Intent i=new Intent(MainActivity.this,Navigation.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Toast.makeText(getApplicationContext(),"Username or password Mismatch",Toast.LENGTH_LONG).show();
}
});
}
How can i solve this am i did anything wrong in this code?
http://182.72.198.001:8080/MyLogin/login/xxxxxx/yyyyyy
If you have to form the above url then you have to send the username and password in url path. So, your Retrofit interface should look like this:
public interface MyInterface {
#GET("login/{userName}/{password}")
Call<ResponseBody> LoginValidation(#Path("userName") String username,
#Path("password") String password);
}
Using
#GET("login/")
Call<ResponseBody> LoginValidation(#Query("userName") String username, #Query("password") String password);
Your URL becomes: http://182.72.198.001:8080/MyLogin/login/?userName=xxxxxx&password=yyyyyy
To exact call as you need, use this (as answered by #Avijit Karmakar )
public interface MyInterface {
#GET("login/{userName}/{password}")
Call<ResponseBody> LoginValidation(#Path("userName") String username,
#Path("password") String password);
}
Using this method you will get the exact result which you want.
i want to send string from app to server with retrofit 2, and get back return values. what is the problem?
but it doesn't work.
Retrofit retrofit = new Retrofit.Builder().baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
RatingApiService retrofitService=retrofit.create(RatingApiService.class);
Call<String> call = retrofitService.registration("saeed","ali");
call.enqueue(new Callback<String>() {
#Override
public void onResponse(Call<String> call, Response<String> response) {
if(response!=null){
Log.i("upload","is success:" +response.body());
}else{
Log.i("upload","response is null");
}
}
#Override
public void onFailure(Call<String> call, Throwable t) {
Log.i("upload","onFailure: "+t.getMessage());
}
});
Interface:
public interface RatingApiService {
#FormUrlEncoded
#POST("android/add2/{email}{password}")
Call<String> registration(#Path("email") String email, #Path("password") String password);
}
Instead of using parameters to pass your data; put it in a req.body, then send it. By doing so, you can bypass the URL string limit and the code is much more organized.
public interface RatingApiService {
#Headers("Content-Type: application/json") //Must be set to application/json so req.body can be read.
#POST("android")
Call<String> registration(#Body UserRegistrationRequest body);
}
Now, you might ask what is the " UserRegistrationRequest" class? that will be the object class that will be sent as a JSON object. We define it by:
public class UserRegistrationRequest {
final String email;
final String password;
UserRegistrationRequest(String email, String password){
this.email = email;
this.password = password;
}
}
And then the final step. This is how you convert the object to a JSON object and send it to your server.
UserRegistrationRequest userRegistrationRequest = new UserRegistrationRequest(
RegisterNameFragment.sFirstName, RegisterNameFragment.sLastName, RegisterEmailFragment.sEmail,
RegisterPasswordFragment.sPassword, RegisterAgeFragment.sAge);
Call<Void> call = retrofit.insertUserRegistration(userRegistrationRequest);
call.enqueue(new Callback<UserRegistration>() {
#Override
public void onResponse(Call<UserRegistration> call, Response<UserRegistration> response) {
Log.d("blue", "Data is sent");
}
#Override
public void onFailure(Call<UserRegistration> call, Throwable t) {
Log.d("blue", "fail");
}
});
You need to add #Body annotation to your method like below.
#POST("users/new")
Call<User> createUser(#Body User user);
The content of #Body is sent to server as request body.
If you want to send email and password to server, you should create object that contains such data and use the object in the #Body annotation.
I am trying to implement a POST request via Retrofit, but the approach seems to be wrong, I guess. I followed the steps I used for GET request:
I defined the end point:
public interface GitHubEmailAPI {
#POST("/users/{user}")
Call<GitHubEmail> postEmail(#Field("email") String email);
}
The model:
public class GitHubEmail {
#SerializedName("email")
private String email;
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
And the calling:
public void postEmail (){
GitHubEmailAPI apiService =
ApiClient.getClient().create(GitHubEmailAPI.class);
final Call<GitHubEmail> callEmail = apiService.postEmail
(String.valueOf(enterEmailEt.getText()));
callEmail.enqueue(new Callback<GitHubEmail>() {
#Override
public void onResponse(Call<GitHubEmail> call, Response<GitHubEmail> response) {
testTV.setText(callEmail.toString());
}
#Override
public void onFailure(Call<GitHubEmail> call, Throwable t) {
Log.e("Email", t.toString());
}
});
I am using the github api as a test, not sure if the access token needs to be included as a parameter in the request.
There are some info which you know about Retrofit ....
Your BASE_URL must be end with / .
When you using #Field notation you must put #FormUrlEncoded in Your Api call.
When you using {user} in the API method you have to use #Path("user") String user to relate to url data .
Your POST method URL will be like this #POST("users/{user}").
When your response Callback done the actual Data inside your Response<GitHubEmail> response in this variable. You have to use response.body() to get what you get response from API CALL.
Here is a sample code
#FormUrlEncoded
#POST("users/{user}")
Call<YourResultPojoClassHere> yourFuntionName(#Field("id") String id,#Path("user") String path);
please take look on below code ....
callEmail.enqueue(new Callback<GitHubEmail>() {
#Override
public void onResponse(Call<GitHubEmail> call, Response<GitHubEmail> response) {
if (response.isSuccessful()) {
if (response.body().getSuccess())
Toast.makeText(ClassName.this, response.body().getMessage(), Toast.LENGTH_SHORT).show();
else
Toast.makeText(ClassName.this, response.body().getMessage(), Toast.LENGTH_SHORT).show();
} else
Toast.makeText(ClassName.this, "Sorry for inconvince server is down", Toast.LENGTH_SHORT).show();
}
#Override
public void onFailure(Call<GitHubEmail> call, Throwable t) {
Toast.makeText(ClassName.this, "Check your Internet connection", Toast.LENGTH_SHORT).show();
}
}
});
For POST in retrofit you must include #FormUrlEncoded
#FormUrlEncoded
#POST("path_here")
Call<ResponseBody> function_name(#Field("data") String data);