Retrofit converts POST in GET request when URL is like this
https://www.example.com/index.php?route=api/account/login
Found the solution
#FormUrlEncoded
#POST("index.php")
Call<String> login(#QueryMap(encoded=true) Map<String, String> options,#Field("email") String username,#Field("password") String password);
and calling will be like this
Map<String, String> map = new HashMap<>();
map.put("route","restapi/account/login");
Call<String> call = mAPIService.login(map, email, password);
Related
I have a post method in API, I want to post the data to the API as JSON raw. When I am testing from postman it is working correctly. From my its getting different response.
Map<String, String> paramObject = new HashMap<>();
paramObject.put("username", "jino");
paramObject.put("password", "12345");
paramObject.put("confirmpassword", "12345");
paramObject.put("email", "jino#gmail.com");
paramObject.put("phone", "1234567898");
UserService service = RetrofitInstance.getRetrofitInstance().create(UserService.class);
Call<ResponseBody> call = service.signUp(paramObject);
Service
#POST("addnewuser.php")
Call<ResponseBody> signUp(#Body Map<String, String> body);
Pass JsonObject instead of Map:
public interface RetrofitService {
#POST("addnewuser.php")
Call<ResponseBody> signUp(#Body JsonObject body);
}
Create it as following:
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("username", "jino");
jsonObject.addProperty("password", "12345");
jsonObject.addProperty("confirmpassword", "12345");
jsonObject.addProperty("email", "jino#gmail.com");
jsonObject.addProperty("phone", "1234567898");
And call your Retrofit service:
Call<ResponseBody> call = service.signUp(jsonObject);
I'm trying to make a PUTrequest using retrofit. All parameters sent except the data inside the Classic Java object. it contains a and other data but the backend not adding any of its parameters. I tried adding the HashMap as an individual part "working_session_pauses_attributes" but also not sent. Any solution or suggestion?
Thanks in advance
#Multipart
#PUT(WORKING_SESSION_PATH)
Observable<Response<WorkingSession>> updateWorkingSession(#Path(LOCATION_ID_VARIABLE) String locationId,
#Path(EMPLOYEE_ID_VARIABLE) String employeeId,
#Path(WORKING_SESSION_ID_VARIABLE) String workingSessionId,
#Part("working_session_id") String working_session_id,
#Part("ends_at") String ends_at,
#Part("starts_at") String starts_at,
#Part("secure_id") String secure_id,
#Part ("tag_ids[]") Long[] tag_ids,
#Part ("working_session_pauses_attributes") HashMap<Integer, UpdateBreakDataModel> working_session_pauses_attributes,
#Part ("data") CreateWorkingSessionRequestBody CreateWorkingSessionRequestBody,
#Part MultipartBody.Part end_signature,
#Part MultipartBody.Part start_signature_break,
#Part MultipartBody.Part end_signature_break);
I don't know what are you doing, you want post request but you are using put, please check. I am showing you my code how i am sending data using Hash map.
This is my method declaration:
#GET(ApiConstant.REQUEST_FORM_CHECK_OUT_ID)
Call<CheckOutIdResponseParent> callRequestFormCheckoutId(#QueryMap Map<String, String> params);
& here i am calling that method using hashmap.
Map<String, String> params = new HashMap<>();
params.put("category_id", categoryId);
params.put("currency", currency);
params.put("language", language);
ServiceApi mRetrofitCommonService = RetrofitClient.getInstance();
Call<ProductListParentResponse> call = mRetrofitCommonService.callProductListApi(params);
I have an endpoint where I PUT some data, where the Content-Type should be form-data.
I'm using
#FormUrlEncoded
#PUT("/api/v1/clients/profile/all_details")
Call<ResponseBody> postUserProfile(#FieldMap Map<String, String> userParams);
but while sending the request, the form-data is encoded like
food_allergy=%5Beggs%2C%20milk%2C%20nuts%2C%20none%5D&diet_prefer=Non%20Vegetarian&age=25&exercise_level=Moderate&email=Email&name=Veeresh&height=175&prompt-qgreet3=I%27m%20ready%21&gender=Female&health_condition=%5Bdiabetes%2C%20PCOD%5D&weight=69
How do I remove the encoding?
I tried this blog
https://futurestud.io/tutorials/retrofit-send-data-form-urlencoded-using-fieldmap
You can first of all replace all the % by using
string.replace("%","");
And do the rest the same way.
If you don't want to encode the form data then you can try like this
#PUT("/api/v1/clients/profile/all_details")
Call<ResponseBody> postUserProfile(#QueryMap Map<String, String> userParams);
EDIT 1
#Multipart
#PUT("/api/v1/clients/profile/all_details")
Call<ResponseBody> postUserProfile(#Part(username) RequestBody username, #Part(password) RequestBody password);
And here is how to get requestBody from String.
String username = "username";
RequestBody body = RequestBody.create(MediaType.parse("text/plain"), username);
String password = "password";
RequestBody body = RequestBody.create(MediaType.parse("text/plain"), password);
#FieldMap has an element called encoded which is false by default.
If you set it to true, you're saying my data is already encoded and I don't want Retrofit to handle the encoding.
#FieldMap(encoded = true) Map<String, String> userParams
I am trying to send multiple parameters (as I usually do) with #QueryMap but via POST this time using retrofit.
Retrofit API
#POST("/request.php")
void sendRequest(#QueryMap Map<String, String> parameters, retrofit.Callback<RequestSendResponse> callback);
Map that is being send
public static Map<String, String> parametersSendRequest(Context sender, Request request)
{
Map <String, String> parameters = new HashMap<>();
Operator operator = AppConfig.config().operator;
parameters.put("user_name", request.user_name);
parameters.put("user_surname", request.user_surname);
parameters.put("user_gender", request.user_gender);
parameters.put("user_relationship", request.user_relationship);
parameters.put("user_dob", request.user_dob);
parameters.put("operator_name", operator.name);
parameters.put("request_photoid", request.request_photoid);
parameters.put("request_user_content", request.request_user_content);
parameters.put("request_title", request.request_title);
parameters.put("uuid", UUID(sender));
parameters.put("response_type", "json");
parameters.put("platform", "android");
parameters.put("mode", "send");
return parameters;
}
Server result
{"POST":[],"GET":{"operator_name":....}}
I can see that even the method is sent to POST, #QueryMap causes these parameters to be sent over GET. Even when I use #Body instead of #QueryMap, retrofit converts my #QueryMap to a JSON object, which is not I want.
All I want to do is to send param1=value1¶m2=value2 on my request body, instead of a JSON object (Using my Map<String, String>)
to send parameters using POST (#FormUrlEncoded and #FieldMap)
#FormUrlEncoded
#POST("/request.php")
void sendRequest(#FieldMap Map<String, String> parameters, retrofit.Callback<RequestSendResponse> callback);
This one works for me
#FormUrlEncoded
#POST("/profile/")
void getUserProfile(#Field("whatever")String whatever, Callback<Response> callback);
Pay special attention to the final slash after "profile". I had problems because I was not adding it. Hope it helps.
I am working on volley library: http://developer.android.com/training/volley/index.html
Get and 'Post methods without parameters' working fine. But when parameters are given, volley does not execute the form, and acts like form itself is a jsonObject:
com.android.volley.ParseError: org.json.JSONException: Value Login< of type java.lang.String cannot be converted to JSONObject
I have tried both overriding getParams() method:
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("username", username);
params.put("password", password);
return params;
}
And instantiating the object with parameter:
Map<String, String> params2 = new HashMap<String, String>();
params2.put("username", username);
params2.put("password", password);
JsonObjectRequest jsonObjectRequest1 = new JsonObjectRequest(Request.Method.POST, LOGIN_URL, new JSONObject(params2), new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
//onResponse
}
});
None of them worked. I am guessing my problem is about the content types. Volley library uses application/json while my php codes use name-value pairs.
I have seen these two questions but sadly they did not solve my case:
Google Volley ignores POST-Parameter
Volley Post JsonObjectRequest ignoring parameters while using getHeader and getParams
When you use JsonObjectRequest, you are saying that the content you are posting is a JSON Object and the response you expect back will also be a JSONObject. If neither of these are true, you need to build your own Request<T> and set the values you need.
The error you are seeing is because the response from the server is not a valid JSON response.