Volley JsonObjectRequest send headers in GET Request - android

I am trying to send some authentication headers from GET request and I tried using Volley JsonObjectRequest call :
Map<String,String> params=new HashMap<String,String>();
params.put("token","fghjbvjhnjjk");
activity.showDialog();
JsonObjectRequest req = new JsonObjectRequest(Request.Method.GET,url,
new JSONObject(params), new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(tag, response.toString());
activity.hideDialog();
try {
activity.onRequestServed(response, code);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(tag, "Error: " + error.getMessage());
Log.e(tag, "Site Info Error: " + error.getMessage());
Toast.makeText(activity.getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
activity.hideDialog();
try {
activity.onRequestServed(null,code);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
req.setShouldCache(true);
But its showing:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.hashCode()' on a null object reference
at com.android.volley.Request.<init>(Request.java:136)
at com.android.volley.toolbox.JsonRequest.<init>(JsonRequest.java:58)
at com.android.volley.toolbox.JsonObjectRequest.<init>(JsonObjectRequest.java:47)
I read somewhere that you can pass headers by making a hashmap and thus create a new JsonObject with that parameter. Maybe that will work on a POST request. Please help..

Well, the thing is simple and very precise. Passing headers to either GET or POST request, you need to override getHeaders method in JsonObjectRequest Class. This is how it will be done:
JsonObjectRequest req = new JsonObjectRequest(Request.Method.GET,url,
null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(tag, response.toString());
activity.hideDialog();
try {
activity.onRequestServed(response, code);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(tag, "Error: " + error.getMessage());
Log.e(tag, "Site Info Error: " + error.getMessage());
Toast.makeText(activity.getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
activity.hideDialog();
try {
activity.onRequestServed(null,code);
} catch (JSONException e) {
e.printStackTrace();
}
}
}) {
/**
* 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("key", "Value");
return headers;
}
};

Related

Error null! from Volley on Http Post Request with JSon object

I'm getting a Null Exception with JSon object from Volley
I filled the JSon object before it is used, and not in the parameterlist.
public static void SendPost6(final Context context){
final String TAG= "-->Error-->";
String url = "http://192.168.44.120/test_php_neuer_user.php";
RequestQueue queue = Volley.newRequestQueue(context);
JSONObject userObject = new JSONObject();
JSONObject paramsObject = new JSONObject();
try {
paramsObject.put("name", "Name");
paramsObject.put("email", "EMail");
userObject.put("user",paramsObject);
}
catch (JSONException e){
Toast.makeText(context, "JSON-Error:" + e.toString(), Toast.LENGTH_LONG).show();
e.printStackTrace();
}
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, url,
userObject,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Toast.makeText(context, "Volley Response:" + response.toString(), Toast.LENGTH_LONG).show();
}},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//handle errors#
Log.d(TAG, "Failed with error msg:\t" + error.getMessage());
Log.d(TAG, "Error StackTrace: \t" + error.getStackTrace());
Toast.makeText(context, "Volley Error:" + error.getMessage(), Toast.LENGTH_LONG).show();
error.printStackTrace();
try {
byte[] htmlBodyBytes = error.networkResponse.data;
Log.e(TAG, new String(htmlBodyBytes), error);
} catch (NullPointerException e) {
e.printStackTrace();
}
}
});
queue.add(request);
//AppController.getInstance().addToRequestQueue(request);
I want to add the json object request into the queue to perform http-post. Volley Error is "null"
The firewall blocked the network access. This is why i'm getting response null. Solved.

No response after putting in Header in request

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.

Send token header in json object paramater Volley post

I am using post method in volley. I searched and found that getHeader() is used to send header in request.The solution was to use JSONObject request instead of string request(which i am using currently) but is there a way of sending header through this method? Because in that case I will have to modify a lot of code in many classes. Sorry for the English, I am not a native speaker.
The request parameter is a json object. I am sending the parameters using following code.
mRequestQueue = Volley.newRequestQueue(getContext());
mStringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("Response", "onResponse: " + response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.i("This is the error", "Error :" + error.toString());
}
})
{
#Override
public String getBodyContentType() {
return "application/json";
}
#Override
public byte[] getBody() throws AuthFailureError {
HashMap<String, String> params2 = new HashMap<String, String>();
params2.put("AssigneeId",userid);
params2.put("IssueStatus", "5");
return new JSONObject(params2).toString().getBytes();
}
};
mRequestQueue.add(mStringRequest);
This request also has StringRequest. Please use the getHeaders() in this way:
public void requestWithSomeHttpHeaders() {
RequestQueue queue = Volley.newRequestQueue(this);
String url = "http://www.somewebsite.com";
StringRequest getRequest = new StringRequest(Request.Method.GET, 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) {
// TODO Auto-generated method stub
Log.d("ERROR","error => "+error.toString());
}
}
) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("User-Agent", "Nintendo Gameboy");
params.put("Accept-Language", "fr");
return params;
}
};
queue.add(getRequest);
}
For JsonObjectRequest:
JsonObjectRequest req = new JsonObjectRequest(Request.Method.GET,url,
null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(tag, response.toString());
activity.hideDialog();
try {
activity.onRequestServed(response, code);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(tag, "Error: " + error.getMessage());
Log.e(tag, "Site Info Error: " + error.getMessage());
Toast.makeText(activity.getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
activity.hideDialog();
try {
activity.onRequestServed(null,code);
} catch (JSONException e) {
e.printStackTrace();
}
}
}) {
/**
* 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("key", "Value");
return headers;
}
};

JSON request not responded

I have a webservice which returns json files. If I call this url (http://192.168.178.67:8080/simplestock/webapi/swipeService/swipes/Aktien) on my smartphone browser, I will get a json array back.
Now I've tried to get this json in my android project with this code:
JsonArrayRequest jsonObjectRequest = new JsonArrayRequest
(Request.Method.GET, url, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d("Success", "onResponse is Called");
try {
Log.d("Get Object: ", response.getJSONArray(1).toString());
} catch (JSONException e) {
e.printStackTrace();
Log.d("Failure", "JSON Error");
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("JSON", "Error");
}
});
The problem is that the respond isn't called and I don't get any error message. I've added the internet permission in the manifest. I test on my smartphone, which is in the same network than the localhost. Anybody got an idea?
In what ever method you are calling your code you need to add the request to the queue: jsonObjectRequest.add(jsonArrayRequest);
Like this:
JsonArrayRequest jsonObjectRequest = new JsonArrayRequest
(Request.Method.GET, url, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d("Success", "onResponse is Called");
try {
Log.d("Get Object: ", response.getJSONArray(1).toString());
} catch (JSONException e) {
e.printStackTrace();
Log.d("Failure", "JSON Error");
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("JSON", "Error");
}
});
jsonObjectRequest.add(jsonArrayRequest);

Volley What Request Type to use for the format

I'm New to android Volley. I accessing a API server and its response is JSON.
The response JSON is like this\
{
status:true,
data : [{
id:1,
name:'name 1',
},
{
id:2,
name:'name 2 ',
}]
}
I tried using JsonObjectRequest & JsonArrayRequest in Volley. Both throws error. What is the Right request type to use and How to parse it?
You will need to use a JsonObjectRequest for this, if it is a post request use the following
try{
JSONObject jsonBody = new JSONObject("add json body to post");
RequestQueue mQueue = Volley.newRequestQueue(getApplicationContext());
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(LookUp.url, jsonBody,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// pDialog.cancel();
try{
if(response.getString("status").equals("true")){
JSONArray jsonArray=response.getJSONArray("data");
for(int i=0;i<jsonArray.length();i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String name=jsonObject.getString("name");
}
}
}
catch (JSONException error){
Log.e("TAGJE", error.getMessage());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("TAGE", error.getMessage(), error);
}
}){
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("Content-Type", "application/json");
return params;
}
};
mQueue.add(jsonObjectRequest);
}
catch (JSONException ex){
ex.printStackTrace();
}
and for a get request follow this
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.GET,
url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
try{
if(response.getString("status").equals("true")){
JSONArray jsonArray=response.getJSONArray("data");
for(int i=0;i<jsonArray.length();i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String name=jsonObject.getString("name");
}
}
}
catch (JSONException error){
Log.e("TAGJE", error.getMessage());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
});

Categories

Resources