Unexpected response code 500 for my api link - android

i have a server side api method which accept Model class as a parameter
which does work fine i have checked it but from android i am confused how to send a Model class as a parameter?
public class Login extends AppCompatActivity {
EditText email, password;
String Email, Pass;
Button loginbtn;
String URL = "https://192.168.0.102/api/campaign/Logins";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
handleSSLHandshake();
email = findViewById(R.id.input_email);
password = findViewById(R.id.password);
loginbtn = findViewById(R.id.login_button);
final RequestQueue queue = Volley.newRequestQueue(this);
loginbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Email = email.getText().toString();
Pass = password.getText().toString();
StringRequest postRequest = new StringRequest(Request.Method.POST, URL,
new Response.Listener<String>()
{
#Override
public void onResponse(String response) {
// response
Log.d("Response", response);
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
// error
Log.d("Error.Response", error.toString());
}
}
) {
#Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<>();
params.put("email", Email);
params.put("password", Pass);
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/json; charset=utf-8");
return headers;
}
};
queue.add(postRequest);
}
});
This is what i have tried i know the problem is from the server side can anyone help me what i am thinking is the problem or is there anything else ?

You just need to add a JSONObject with the post parameters as key-value pairs in the JSON Object. Here is the example for you:
JSONObject postparams = new JSONObject();
postparams.put("keyX", "valueX")
postparams.put("KEY", "Value")
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
url, postparams,
new Response.Listener() {
#Override
public void onResponse(JSONObject response) {
//Success Callback
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//Failure Callback
}
});

Related

Android Studio Error in connect to asp.net API

i trying to connect my project in android studio to Asp.net API
and i'm using Volley Lib to Get Json Request but he did'nt read the response
and I getting this massage in Log
((( E/Volley: [352] BasicNetwork.performRequest:
Unexpected response code 400 for http://10.10.4.150:61511/api/Feedback/30)))
-Api work correctly i`m test with postman
enter image description here
public static final String GET_BY_ID = "http://10.10.4.150:61511/api/Feedback/30";
EditText id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
id = (EditText) findViewById(R.id.idtxt);
}
public void click(View v) {
if (v.getId() == R.id.btnget) {
insertData (id.getText().toString()) ;
}
}
public void insertData (String value){
HashMap<String,String> param = new HashMap<String, String>();
param.put("id",value);
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, GET_BY_ID,null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("Response", response.toString());
try {
JSONObject ob = response.getJSONObject("userId") ;
int name = ob.getInt("userId");
Toast.makeText(getBaseContext(),name,Toast.LENGTH_LONG).show();
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getBaseContext(),e.getMessage(),Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getBaseContext(),error.getMessage(),Toast.LENGTH_LONG).show();
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json; charset=utf-8");
headers.put("User-agent", "My useragent");
return headers;
}};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(request);
}
}

How to send parameters to backend, and get response message, using GET method in volley, android?

I want to send three parameters "guestEmail", "latitude" and "longitude" to backend and get a message of success from backend if it is successful.
I have tried doing this:
public void myGetFunc()
{
final String url = "....";
// prepare the Request
JsonObjectRequest getRequest = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>()
{
#Override
public void onResponse(JSONObject response) {
// display response
Log.d("Response", response.toString());
Toast.makeText(getApplicationContext(), response.toString(), Toast.LENGTH_SHORT).show();
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Error.Response", response);
}
}
)
{
#Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<String, String> ();
params.put("guestEmail", "abc#xyz.com");
params.put("latitude", "12");
params.put("longitude", "12");
return params;
}
};
// add it to the RequestQueue
queue.add(getRequest);
}
This method is invoked when the 'SOS' button is clicked.
But right now, nothing happens on clicking the 'SOS' button.
Please help!
If you are going to use GET you query parameters and build the string yourself
private static final String URL = "http://www.test.com?value1={val1}&value2={val2}";
String requestString = URL;
requestString.replace("{val1}", "1");
requestString.replace("{val2}", "Bob");
StringRequest strreq = new StringRequest(Request.Method.GET,
requestString,
new Response.Listener<String>() {
#Override
public void onResponse(String Response) {
// get response
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError e) {
e.printStackTrace();
}
});
Volley.getInstance(this).addToRequestQueue(strreq);
If you are going to use POST us a body
public class LoginRequest extends Request<String> {
// ... other methods go here
private Map<String, String> mParams;
public LoginRequest(String param1, String param2, Listener<String> listener, ErrorListener errorListener) {
super(Method.POST, "http://test.url", errorListener);
mListener = listener;
mParams = new HashMap<String, String>();
mParams.put("paramOne", param1);
mParams.put("paramTwo", param2);
}
#Override
public Map<String, String> getParams() {
return mParams;
}
}
If you want to pass parameters than you need to use POST method otherwise for GET , just pass values in URL itself.

POST request with Volley gives "UnknownHostException"

I'm trying to perform a POST request using Volley, but I keep getting the error com.android.volley.NoConnectionError: java.net.UnknownHostException: Unable to resolve host "<my custom API URL>". No address associated with hostname. The request seems to work using Postman and I have already gave the necessary permissions in the Manifest (both INTERNET and ACCESS_NETWORK_STATE).
I'm using a local server with SequelPro and Laravel.
Here is the Postman working screens:
Postman body
Postman headers
Here is the part of the code of the Login Activity:
public class LoginActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
final EditText emailInput = findViewById(R.id.emailInput);
final EditText passwordInput = findViewById(R.id.passwordInput);
final EditText confirmPasswordInput = findViewById(R.id.confirmPasswordInput);
final Button loginBtn = findViewById(R.id.loginBtn);
loginBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String email = emailInput.getText().toString();
final String password = passwordInput.getText().toString();
final String confirmPassword = confirmPasswordInput.getText().toString();
try {
RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
String URL = "http://lalalaravel.test/api/login";
JSONObject jsonBody = new JSONObject();
jsonBody.put("email", email);
jsonBody.put("password", password);
jsonBody.put("password_confirmation", confirmPassword);
JsonObjectRequest jsonObject = new JsonObjectRequest(Request.Method.POST, URL, jsonBody, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("VOLLEY", response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("VOLLEY", error.toString());
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
final Map<String, String> headers = new HashMap<>();
headers.put("Authorization", "Bearer " + "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImp0aSI6IjM4MmM1OTc5YzFhN2Y1ZDczMjFjMWQwMThhYzBmMTdkZWI1MzlkMjIxN2M2YWRhMDUxNzhlMTcyNmVmOWQwZDM3ZGY2ZTdlNDIxOGUxNmQ5In0.eyJhdWQiOiIxIiwianRpIjoiMzgyYzU5NzljMWE3ZjVkNzMyMWMxZDAxOGFjMGYxN2RlYjUzOWQyMjE3YzZhZGEwNTE3OGUxNzI2ZWY5ZDBkMzdkZjZlN2U0MjE4ZTE2ZDkiLCJpYXQiOjE1MjkyNTg2OTAsIm5iZiI6MTUyOTI1ODY5MCwiZXhwIjoxNTYwNzk0NjkwLCJzdWIiOiIyMSIsInNjb3BlcyI6W119.hyjXMXwRb3GLVJ7w5KBmzwVDzoPcztjXKHOx8fqwN6jOvTfgki_HngAIB3JaG5Xhb7w8mFBX03fUDwzOc2S108SiBTjZ7B14GtYmlC8OgxVkKXcCqJ_0UOZBsgCYo7p7f4HBIgIyZ8StrsNlNbuj_4W5Pz2YY4WitbvDX9LsZFIbdz3vhVlmtR2zKA23hyRGUsWZniB7zLGEvsUt5XA9NNAy9XWySaw7JuRZ4uyYm0bXHrJKHSTmfBd9KOJSdpnWs_9miNvh5g_DJo39L7awAlG7-cb67Ih00bhrmgGAWp6VCEd5h-EhIc-l1qfYT56osDgnYIqMk3cAgIWrYrhrs6-mZ1miXqipk9dClliUO7DBylZW8cRbQ5PQ5xisE_wCMTSUr7VYE_7RyjMzDaZuctf8kHQ_W27ED9tq14NhgvJs4hkpO6Gzr32zyMj-KRan2Fc3O1CYgyJx0OR2LhvXrxp2PxfUSIzR8eGHOGypLicU_suG3Dsz_UG7Kp5EdhP8Ma9eDyWObfU64iFYZsuz58TOBOH2ssH7_PpKHBGmchxQSjpKsIwsjeYpdbVmzXG7cZe2_AOEZpXmlwkaAZLow3_kDPfvuoCIWVsEKfgRs72t3B8fIwSt-vWaXpGYKjGOjf9ZOXpiKjG1XHaur0vLR1eiIXKVFSyn6y42FIlbSqk");
headers.put("Content-Type", "application/json");
return headers;
}
};
queue.add(jsonObject);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
}
Honestly I don't know what to do, Internet is working fine and some of my classmates are doing their requests with iOs with no problem, it shouldn't be a connection problem...

Missing parameters Kairos API with Android Volley POST

I'm trying to use KairosAPI's enroll POST request using Android Volley. However I keep getting Error 1002, image one or more required parameters are missing. I've tried two ways to add the parameters into the body of the JSON, which I've outlined in the code.
This is my code-
public class MainActivity extends AppCompatActivity {
RequestQueue requestQueue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
postRequestToEnrollPersonInGallery();
}
public void postRequestToEnrollPersonInGallery() {
final String appId = "3e12****";
final String appKey = "156e06fd782a3304f085f***********";
String mainUrl = "https://api.kairos.com/";
String enrollRequestUrl = "enroll";
requestQueue = Volley.newRequestQueue(this);
StringRequest stringRequest = new StringRequest(Request.Method.POST, mainUrl + enrollRequestUrl, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("Volley", response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Volley", error.toString());
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("Content-Type", "application/json");
params.put("app_id", appId);
params.put("app_key", appKey);
return params;
}
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("image", "https://s-media-cache-ak0.pinimg.com/originals/c6/c0/04/c6c004ec669d92faa36d8ff447884293.jpg");
params.put("subject_id", "12345");
params.put("gallery_name", "FirstGallery");
/*params.put("image", "\"url\":\"https://s-media-cache-ak0.pinimg.com/originals/c6/c0/04/c6c004ec669d92faa36d8ff447884293.jpg\"");
params.put("subject_id", "\"subject_id\":\"12345\"");
params.put("gallery_name", "\"gallery_name\":\"FirstGallery\""); -- i tried this too*/
return params;
}
};
requestQueue.add(stringRequest);
}
}
You aren't posting JSON.
You can either
1) Learn to use JsonObjectRequest
final JSONObject body = new JSONObject();
body.put(... , ...);
Request request = new JsonObjectRequest(url, body, ...);
2) Actually post a JSON String.
StringRequest request = new StringRequest(...) {
#Override
public byte[] getBody() throws AuthFailureError {
JSONObject params = new JSONObject();
params.put("image", "https://s-media-cache-ak0.pinimg.com/originals/c6/c0/04/c6c004ec669d92faa36d8ff447884293.jpg");
params.put("subject_id", "12345");
params.put("gallery_name", "FirstGallery");
return params.toString().getBytes();
}
#Override
public String getBodyContentType() {
return "application/json";
}
};

Code response code 400 when sending POST params and headers using Volley

I have tried every single method available on stackoverflow but result remains the same.
I want to send params and also api key in the Authorization field of header using volley.
Here is the code snippet.
holder.comment_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String POSTCOMMENT_URL = Utility.getIPADDRESS()+"comments";
volleySingleton = VolleySingleton.getInstance();
requestQueue = volleySingleton.getRequestQueue();
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, POSTCOMMENT_URL, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.e("Response: " , response.toString());
Toast.makeText(myApplication.getApplicationContext(),response.toString(),Toast.LENGTH_LONG).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(myApplication.getApplicationContext(),"Error", Toast.LENGTH_LONG).show();
}
}){
#Override
public String getBodyContentType() {
return "application/x-www-form-urlencoded; charset=UTF-8";
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("Authorization", getApiKey() );
return params;
}
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put("pid", "39");
params.put("comment", "mobile testing");
return params;
}
};
requestQueue.add(jsonObjectRequest);
}
});
I'm getting this error:
[5333] BasicNetwork.performRequest: Unexpected response code 400 for http://www.XXXXXXXXXXX.com/comments
I have already tested the endpoint using Advanced Rest client, it works and returns the JsonObject with previously added comment.
Here are the results:
{
"error": false
"message": "comment added successfully added!"
"comment_id": "12"
"user_id": "12"
"pid": "39"
"comment": "testing for stackoverflow"
"date of comment": "2016-07-30 13:49:08"
}
Ok, after a long research and stupid rather valuable changes, it finally worked for me.
Here is the working code:
holder.comment_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View view) {
final String api_key = getApiKey();
String POSTCOMMENT_URL = Utility.getIPADDRESS()+"comments";
volleySingleton = VolleySingleton.getInstance();
requestQueue = volleySingleton.getRequestQueue();
StringRequest stringRequest = new StringRequest(Request.Method.POST, POSTCOMMENT_URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(myApplication.getApplicationContext(),response,Toast.LENGTH_LONG).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(myApplication.getApplicationContext(),error.toString(),Toast.LENGTH_LONG).show();
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("Authorization", api_key);
return params;
}
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put("pid", "40");
params.put("comment", "testing");
return params;
}
};
requestQueue.add(stringRequest);
}
});
Note: It worked for me, I'm not sure about others.
Changes are: Change JsonObjectRequest to StringRequest and removing any Content-Type doesn't make any difference, so I removed it.
Also, make sure all the params have some values i.e test it by logging.

Categories

Resources