No response after putting in Header in request - android

My code as follows:
public void getProfile(){
String LOGIN_REQUEST_TAG = "LOGIN_REQUEST_TAG";
String url = Constants.API_URL + "/users/profile";
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("Login Response:", response.toString());
JSONObject responseOject = response;
if(responseOject.has("response")){
try {
Log.d("Data Response", responseOject.getString("response"));
} catch (JSONException e) {
e.printStackTrace();
}
}else if(responseOject.has("error")){
try {
errorMessage = responseOject.getString("error");
new AlertDialog.Builder(MainActivity.this)
.setTitle("Error")
.setMessage(errorMessage)
.setNegativeButton("OK", null)
.show();
} catch (JSONException e) {
e.printStackTrace();
}
}else{
//Server error. Come back again later
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.e("Error at login: ", error.getMessage());
}
/**
* Passing some request headers
*/
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json");
headers.put("Authorization", "Bearer DGZjaza3saxL98g9ATRUQsolCxEZPBUd");
return headers;
}
});
AppSingleton.getInstance(getApplicationContext()).addToRequestQueue(jsonObjectRequest,LOGIN_REQUEST_TAG);
The code works initially but after we added headers which are required by the api request, the code above didn't seem to work.
Did I write the headers code above wrongly? Thanks for your help.
Error from logcat as follows:
BasicNetwork.performRequest: Unexpected response code 401

i think you shouldn't place the getHeader() inside the constructor of JsonObjectRequest. It should be placed inside the anonymous class block
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(
Request.Method.GET,
url,
null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("Login Response:", response.toString());
JSONObject responseOject = response;
if(responseOject.has("response")){
try {
Log.d("Data Response", responseOject.getString("response"));
} catch (JSONException e) {
e.printStackTrace();
}
}else if(responseOject.has("error")){
try {
errorMessage = responseOject.getString("error");
new AlertDialog.Builder(MainActivity.this)
.setTitle("Error")
.setMessage(errorMessage)
.setNegativeButton("OK", null)
.show();
} catch (JSONException e) {
e.printStackTrace();
}
}else{
//Server error. Come back again later
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.e("Error at login: ", error.getMessage());
}
}
){
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json");
headers.put("Authorization", "Bearer DGZjaza3saxL98g9ATRUQsolCxEZPBUd");
return headers;
}
};
In case you wanna learn more, the inheritance hierarchy of JsonObjectRequest in volley is Request -> JsonRequest -> JsonObjectRequest . The method you are overriding getHeaders() is derived from the Request base class.

Related

How to fix JSONException Error in Volley library?

I am trying to send a JSON object request with two parameters and in response trying to get an array from the api call. However, I am getting exception parse error in Error listener. A post request is sent when the button is clicked. The func takes two parameters but fails to get response, the function directly goes to on response error listener
private void validate_log(String num) {
/*buttonNumCheck.setVisibility(View.INVISIBLE);
final ProgressBar pBar=(ProgressBar)findViewById(R.id.progressBarLogin);
pBar.setVisibility(View.VISIBLE);*/
buttonNumCheck.setInProgress(true);
buttonNumCheck.setEnabled(false);
final String Org_id="81";
final String url="http://xya/api";
RequestQueue rq=Volley.newRequestQueue(this);
JSONObject js=new JSONObject();
try {
js.put("parm1", num);
js.put("parm2", Org_id);
final String requestBody=js.toString();
} catch (JSONException e) {
e.printStackTrace();
}
JsonObjectRequest jsonObjReq=new JsonObjectRequest(
Request.Method.POST, url, js,
new Response.Listener<JSONObject>() {
public void onResponse(JSONObject response) {
buttonNumCheck.setEnabled(true);
buttonNumCheck.setInProgress(false);
String stresponse=response.toString();
Toast.makeText(getApplicationContext(),"REPOSE="+response,Toast.LENGTH_SHORT).show();
System.out.println("RESPONSE= "+response);
try {
JSONArray heroArray = response.getJSONArray("");
// Toast.makeText(DeviceCheck_Activity.this, "Welcome Back"+ [1], Toast.LENGTH_LONG).show();
} catch (JSONException e) {
e.printStackTrace();
Log.e("Error", "Response Error", e);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(DeviceCheck_Activity.this, "Response error= " + error, Toast.LENGTH_LONG).show();
/*mdToast=MDToast.makeText(getApplicationContext(), "Oops something went wrong!!",
Toast.LENGTH_SHORT, MDToast.TYPE_ERROR);
mdToast.show();*/
buttonNumCheck.setInProgress(false);
buttonNumCheck.setEnabled(true);
Log.e("Error", "Response Error", error);
}
}) {
#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");
return headers;
}
};
jsonObjReq.setShouldCache(false);
jsonObjReq.setRetryPolicy(new DefaultRetryPolicy(20 * 1000, 0, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
rq.add(jsonObjReq);
}
The error response I am getting is
com.android.volley.ParseError: org.json.JSONException: Value [{"store_id":11,"store_name":"Gomati District Main Store"},{"store_id":13,"store_name":"Main Seed Store"}] of type org.json.JSONArray cannot be converted to JSONObject
Your Problem can be solved in 2 ways :
First:)
Using JSONArrayRequest instead of JSONbjectRequest.
Your JSONObjectRequest returns an JSONObject response while your response is an JSONArray therefore java can not convert it and your application crashes.
Change you request as below:
JSONArrayRequest jsonArrReq=new JSONArrayRequest(//changed
Request.Method.POST, url, js,
new Response.Listener<JSONArray>() {
public void onResponse(JSONArray response) {
JSONArray heroArray = response;//changeed
/* rest of your code */
} catch (JSONException e) {
e.printStackTrace();
Log.e("Error", "Response Error", e);
}
}
},
jsonArrReq.setShouldCache(false);
jsonArrReq.setRetryPolicy(new DefaultRetryPolicy(20 * 1000, 0, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
rq.add(jsonArrReq);
Second :)
Using StringRequest instead of JSONObjectRequest. String request returns an String response which lets you do what ever you want with your response.
Change you request as below :
StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONArray heroArray = new JSONArray(response);
/* rest of your code */
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Error", "Response Error", error);
/*rest of your code */
}
}) {
#Override
public byte[] getBody() throws AuthFailureError {
try {
return requestBody == null ? null : js.getBytes("utf-8");
} catch (UnsupportedEncodingException uee) {
VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", js, "utf-8");
return null;
}
}
#Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
String responseString = "";
if (response != null) {
responseString = String.valueOf(response.statusCode);
// can get more details such as response.headers
}
return Response.success(responseString, HttpHeaderParser.parseCacheHeaders(response));
}
};
}
stringRequest.setShouldCache(false);
stringRequest.setRetryPolicy(new DefaultRetryPolicy(20 * 1000, 0, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
rq.add(stringRequest);
Use the JsonArrayRequest like thisas your response is JsonArray .
JsonArrayRequest jsonObjReq = new JsonArrayRequest(Request.Method.POST, url, js,
new Response.Listener<JSONArray>() {
public void onResponse(JSONArray response) {
buttonNumCheck.setEnabled(true);
buttonNumCheck.setInProgress(false);
String stresponse = response.toString();
try {
for (int i = 0; i < response.length(); i++) {
JSONObject object = response.getJSONObject(i);
String id = object.getString("store_id");
}
} catch (JSONException e) {
e.printStackTrace();
Log.e("Error", "Response Error", e);
}
}
}
Tried all the solutions didn't worked but thank you guys for your help. I actually found the solution from another question posted in stack overflow page. Here is the solution:
RequestQueue requestQueue=Volley.newRequestQueue(getApplicationContext());
StringRequest stringRequest=new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
//JSONArray jsonArray_1=new JSONArray(response);
System.out.println("RESPONSE= " + response);
JSONArray jsonArray=new JSONArray(response);
json_stringarr=new String[jsonArray.length()];
if(jsonArray.length()>0) {
for (int i=0; i < jsonArray.length(); i++) {
JSONObject jsonObject1=jsonArray.getJSONObject(i);
//String web_page=jsonObject1.getString("awb_no");
String store_id=jsonObject1.getString("store_id");
String store_name=jsonObject1.getString("store_name");
json_stringarr[i]=store_id+" - "+store_name;
Toast.makeText(getApplicationContext(), "RESPOBBSE= " + json_stringarr[i], Toast.LENGTH_SHORT).show();
System.out.println("JSON ARRAY=" + json_stringarr[i]);
System.out.println("JSON Object=" + jsonObject1);
}
}
else{
Toast.makeText(getApplicationContext(),"Login ceredentils are incorrect",Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
MDToast mdToast=MDToast.makeText(getApplicationContext(), "Something went wrong!!", Toast.LENGTH_SHORT, MDToast.TYPE_WARNING);
mdToast.show();
error.printStackTrace();
}
}) {
#Override
public byte[] getBody() {
// String body="{\"param1\":"+num+",\"param2\":\"81"\"}";
String body="{\"parm1\":"+num+",\"parm2\":\"81\"}";
return body.getBytes();
}
/*#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("param1", num);
params.put("param2", Org_id);
return params;
}*/
#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");
return headers;
}
};
I did it by sending a String request and then overriding the getBody() method and then it worked like a charm. Thanks again for all your help.

How do i send body data with a JsonObjectRequest? Android-Volley library

I am trying to send data to my server. I create a JsonObject and I pass it as a parameter when creating the JsonObjectRequest. It doesn't give any error, but it is not returning anything. Tried with postman and it is working fine.
This is my code:
JSONObject jsonBody = new JSONObject();
try {
jsonBody.put("firstname", "asd");
jsonBody.put("lastname", "asd");
jsonBody.put("id", "1");
} catch (JSONException e) {
e.printStackTrace();
}
//creating a JsonObjectRequest
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, showPlayersUrl,
jsonBody, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
JSONArray players;
try{
players = response.getJSONArray("Players");
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue.add(jsonObjectRequest);
}
Ok, found the problem. Server side i wasn't accepting the data as json format. Just had to add this and it works:
$_POST = json_decode(file_get_contents('php://input'), true);
Try it:
RequestQueue queue = Volley.newRequestQueue(this);
private void makeJsonObjReq() {
showProgressDialog();
Map<String, String> postParam= new HashMap<String, String>();
postParam.put("un", "xyz#gmail.com");
postParam.put("p", "somepasswordhere");
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.POST,
Const.URL_LOGIN, new JSONObject(postParam),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
msgResponse.setText(response.toString());
hideProgressDialog();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hideProgressDialog();
}
}) {
#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");
return headers;
}
};
jsonObjReq.setTag(TAG);
queue.add(jsonObjReq);
}

How to use POST request in android Volley library with params and header?

I am trying to learn Volley library for posting data into webservices. I need to implement user registration form, following is the image of postman with parameters and header...
now problem is, i am getting below error
com.android.volley.ServerError
this is my code for volley post method.
public void postNewComment(){
try {
RequestQueue requestQueue = Volley.newRequestQueue(this);
String URL = "http://myurl/api/users";
JSONObject jsonBody = new JSONObject();
jsonBody.put("email", "test1#gmail.com");
jsonBody.put("user_type", "C");
jsonBody.put("company_id", "0");
jsonBody.put("status", "A");
jsonBody.put("password", "123456");
final String requestBody = jsonBody.toString();
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i("VOLLEY", response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
Log.e("VOLLEY", error.toString());
}
}) {
#Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
final Map<String, String> headers = new HashMap<>();
headers.put("Authorization", "Basic " + "My_auth_key");
headers.put("Content-Type", "application/json");
return headers;
}
#Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
String responseString = "";
if (response != null) {
responseString = String.valueOf(response.statusCode);
// can get more details such as response.headers
}
return Response.success(responseString, HttpHeaderParser.parseCacheHeaders(response));
}
};
requestQueue.add(stringRequest);
} catch (JSONException e) {
e.printStackTrace();
}
}
please suggest where am i getting wrong. URL is working correct with postman, also as you can see i need to set 2 headers. I also tried this Url post method with AsyncTask and its working good. Now i need to implement this using volley library. kindly suggest. thank you.
this is my logcat error:
E/Volley: [81910] BasicNetwork.performRequest: Unexpected response code 405 for "Myurl"
**Try this one **
private void sendWorkPostRequest() {
try {
String URL = "";
JSONObject jsonBody = new JSONObject();
jsonBody.put("email", "abc#abc.com");
jsonBody.put("password", "");
jsonBody.put("user_type", "");
jsonBody.put("company_id", "");
jsonBody.put("status", "");
JsonObjectRequest jsonOblect = new JsonObjectRequest(Request.Method.POST, URL, jsonBody, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Toast.makeText(getApplicationContext(), "Response: " + response.toString(), Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
onBackPressed();
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
final Map<String, String> headers = new HashMap<>();
headers.put("Authorization", "Basic " + "c2FnYXJAa2FydHBheS5jb206cnMwM2UxQUp5RnQzNkQ5NDBxbjNmUDgzNVE3STAyNzI=");//put your token here
return headers;
}
};
VolleyApplication.getInstance().addToRequestQueue(jsonOblect);
} catch (JSONException e) {
e.printStackTrace();
}
// Toast.makeText(getApplicationContext(), "done", Toast.LENGTH_LONG).show();
}
}
I have an alternative answer that works pretty well for Android Volley+ library by dworks and Google: See HERE

Volley return 403 error

From two days i am trying to solve this issue but still i have no any result,why each and every time volley returning me 403 error. where i m wrong? i am using postman to check same webservice, it returns success result. But same thing when i am using in Android via volley or httpurlconnection getting 403 error.kindly help me to find my error.
This is my code which i have tried:
StringRequest jsonObjectRequest = new StringRequest(Request.Method.POST, Constant.posturl, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
String result=response;
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
NetworkResponse response = error.networkResponse;
int status = response.statusCode;
}
}) {
#Override
public Map<String, String> getHeaders() {
try {
headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json");
String credentials = Constant.USERNAME + ":" + Constant.PASSWORD;
String auth = "Basic " + Base64.encodeToString(credentials.getBytes(), Base64.DEFAULT);
headers.put("Authorization", auth);
return headers;
} catch (Exception e) {
e.printStackTrace();
return headers;
}
}
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("title", heading_edit_text.getText().toString());
params.put("content", body_edit_text.getText().toString());
params.put("Slug", heading_edit_text.getText().toString());
params.put("date", currentDate);
return params;
}
};
jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(50000, 3, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
requestQueue.add(jsonObjectRequest);
Volley does provide a proper request for this which is called JsonObjectRequest.
String webAddress = "url here";
RequestQueue queue = Volley.newRequestQueue(this); // singletone here
JSONObject object = new JSONObject();
try {
object.put("title", heading_edit_text.getText().toString());
object.put("content", body_edit_text.getText().toString());
object.put("Slug", heading_edit_text.getText().toString());
object.put("date", currentDate);
} catch (JSONException e) {
}
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, webAddress,object, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject object) {
Log.d("RESPONSE", object.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Log.d("RESPONSE", "That didn't work!");
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> header = new HashMap<>();
// content type is not needed here
header.put("Authorization", "value here");
return header;
}
};
queue.add(request);
Change the "Content-Type" of your headers to "application/form-data"
ie,
headers.put("Content-Type", "application/form-data");
I was also face this issue in news api. But when I use Retrfit its work like a charm.

How to read response header's status code and response body in volley library Android

I am using volley library for network calls in Android and jsonObject for sending and getting values from the server.
In my case if I send the correct value, it returns the correct json object, but if I send a wrong input to the server it returns 401 as a request header and response body with error message . But that's not showing in onResponse success method.
here is my code
private void makeLoginReq() {
showProgressDialog();
Map<String, String> postParam = new HashMap<String, String>();
postParam.put("un", user_name.getText().toString());
postParam.put("p", password.getText().toString());
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.POST,
Server.URL+Server.FUNC_LOGIN, new JSONObject(postParam),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("TAG", response.toString());
hideProgressDialog();
try {
if("0".equalsIgnoreCase(response.getString("status")))
{
startActivity(new Intent(ActivityLogin.this,ActivityHome.class));
}else if("1".equalsIgnoreCase(response.getString("status")))
{
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("TAG", "Error: " + error.networkResponse.statusCode);
hideProgressDialog();
Crouton.makeText(ActivityLogin.this, "Server Error Try again", Style.ALERT).show();
}
}) {
/**
* Passing some request headers
* */
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json");
headers.put("charset", "utf-8");
return headers;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(jsonObjReq, tag_json_obj);
}
My need is to get the json response in public void onResponse(JSONObject response) { method }.
Can anyone help me to overcome this problem?
There are a lot sub classes of VolleyError, you can check the error type with instanceOf checking.

Categories

Resources