Can't understand the logic of POST request with AndroidAnnotations - android

I want to use AndroidAnnotations to send POST request. In my POST request I need to send two String parameters - Mail and Phone.
I am trying to do this with following code.
Here is the definition of POST method:
#Post("&Action=login")
LoginWebInfo getLoginWebInfo (TreeMap data);
And here is how I call this method:
TreeMap<String, String> data = new TreeMap<String, String>();
data.put("Mail", email);
data.put("Phone", phone);
return webInteractionWithUserClient.getRegistrationWebInfo(data);
But this code doesn't seem to work. Where is my mistake?

use a multivalue map not a tree
MultiValueMap<String, String> data = new LinkedMultiValueMap<String, String>();
data.add("mail",email);
data.add("Phone", phone);
LoginWebInfo logWebInfo = webInteractionWithUserClient.getRegistrationWebInfo(data);

Related

Unable to save authorization header in Android using Volley

So I am building an Android app which talks to an API.
Whenever a user logs in, I see the response in the log cat which contains the user details including the authentication token but the user gets unauthorized access although the login is successful.
My question is; how do I authorize the user? How do I save the token header in android using volley? This concept is new to me. Please help.
After you login, you need to save the session cookie, access token or whatever your api provides. I usually use SharedPreferences.
Later within your next api Request, you need to override the getHeaders();
JsonObjectRequest volleyRequest = new JsonObjectRequest(url, null, responseListener, errorListener){
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> params = new HashMap<>();
// put your accesstoken if available
params.put("X-CSRF-Token", accessToken);
// put a session cookie if available
params.put("cookie", sessionName + "=" + sessionId);
return params;
}
};

POST request with JSON body in Volley Android

I am using volley library. I have the following API url http://example.com/project/contriller/ and need to post the json request as body {"function":"getList","parameters":{"latitude":"10.0086575","longitude":"76.3187739"},"token":""}to it.
How can send it using Volley?
Please check below two options for that.
Option1
Try to send data in Map variable as below, and put this code just above you are calling request using Post as below.
Map<String, String> postParam= new HashMap<String, String>();
postParam.put("function", "getList");
postParam.put("latitude", "10.0086575");
postParam.put("token", "");
new JsonObjectRequest(url, postParam, new Response.Listener<JSONObject>() { ... });
option2
You can use below to send direct JSON.
final JSONObject jsonData = new JSONObject("{\"function\":\"getList\",\"parameters\":{\"latitude\":\"10.0086575\",\"longitude\":\"76.3187739\"},\"token\":\"\"}");
new JsonObjectRequest(url, jsonData, new Response.Listener<JSONObject>() { ... });

retrofit #POST parameters are sent via GET

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&param2=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.

Unexpected response code 500 for POST method

I am doing an update on the old project & I don't have much knowledge of Android as of now. In project we have Comments section on product.
For comment after sending earlier we had return as 0 (some error) & 1 (success).
Below is the code we were using.
final JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(
Method.POST,
act.getString(R.string.CommentForUserURL),
null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(
JSONObject response) {
Log.d("response done", "done===" + response);
mloading.setVisibility(View.GONE);
if (response != null) {
Comment obj = new Comment();
JSONObject jsonObject = response;
try {
obj.setComment(jsonObject
.getString("Comment"));
Now we have changed the return object from 0/1 to user object.
Does this need need to update JsonObjectRequest to GJSON request? Or object will also get parsed with JsonObjectRequest?
I am asking because when I execute above, I get error as below.
01-25 12:30:21.754: E/Volley(16487): [10114] BasicNetwork.performRequest:
Unexpected response code 500 for
http://new.souqalharim.com/add/CommentForMerchant
Any idea why I am getting this error?
Note: This URL is working fine for iPhone application.
Edit 1
This is post method, so full url is not there. There are few more parameters to add like ?comment=MyComment&userId=123&productId=234. As it is post I am not adding parameters in actual url.
I have those in another methods
#Override
protected Map<String, String> getParams()
throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("productId", productId.toString());
params.put("userId",
mSessionManager.getUserCode().toString());
params.put("comment", GlobalFunctions
.EncodeParameter(med_comments
.getText().toString()));
return params;
}
Full url is as below.
http://new.souqalharim.com/add/CommentForUser?productId=325&userId=5&comment=abcd
I tested this in Mozilla RESTClient and it works fine.
Edit 2
After checking further I found protected Map<String, String> getParams() throws AuthFailureError { is not getting called. Any idea why this is happening?
The problem is below.
final JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(
Method.POST,
act.getString(R.string.CommentForUserURL),
null, new Response.Listener<JSONObject>() {
^^^^
It should be
final JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(
Method.POST,
act.getString(R.string.CommentForUserURL),
new JSONObject(params), new Response.Listener<JSONObject>() {
^^^^^^^^^^^^^^^^^^^^^^
Copy code from protected Map<String, String> getParams() before final JsonObjectRequest.
That's it!!!
Reason is as below.
The JsonObjectRequest is extended JsonRequest which override getBody() method directly, so your getParam() would never invoke, I recommend you extend StringRequest instead of JsonObjectRequest.
your can check this answer for more details.
Actually 500 means Internal server error and this is caused by the Rest-api you are calling and not due to Volley,so check the back-end code.
BasicNetwork.performRequest: Unexpected response code 500
The server receives the correct response, but detects an error, this error is due to the PHP connection file with the database, this code must have the function implemented to hide the values ​​of the query to avoid sql insertion
use this sample code:
<?php
$con = new mysqli('localhost', 'u648230499_wololo', '*********', 'u648230899_ejexample');
if ($con->connect_error) {
echo 'error connect database: ', $con->connect_error;
exit();
}
$participantId = $_POST['participantId'];
$name = $_POST['name'];
$sql = $con->prepare('INSERT INTO participant VALUES (?,?)');
$sql->bind_param('is', $participantId, $name);
$sql->execute();
echo 'OK\n';
$con->close();
?>

Using volley library, cant execute a post method form with parameters

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.

Categories

Resources