Android Studio, Volley I do not get a JSON response - android

I have build a laravel Rest API with a Jason Web Token. Now I want to make a App which sends data to the Webservice. Here I try to authentificate myself (with name email and password) at first but I do not get the token as a answer. I also do not get a error, nothing happens.
private void sendAndRequestResponse() {
try {
JSONObject jsonBody = new JSONObject();
jsonBody.put("name", "ida");
jsonBody.put("email", "ida#gmail.com");
jsonBody.put("password", "secret");
final String mRequestBody = jsonBody.toString();
//RequestQueue initialized
mRequestQueue = Volley.newRequestQueue(this);
mJsonRequest = new JsonObjectRequest(
Request.Method.POST, url, jsonBody,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
answer.setText(response.toString());
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
});
mRequestQueue.add(mJsonRequest);
} catch (JSONException e) {
e.printStackTrace();
}
}

you need to start request queue in order to make the request call.
after
mRequestQueue.add(mJsonRequest);
add following
mRequestQueue.start();

Related

volley authentication errors when attempting to push to the server

I am developing an android app in which I have created a custom API for database. I am using volley for HTTP request. I am getting "com.android.volley.AuthFailureError" error on my onErrorResponse. I have checked the JSONObject in the debugger and it's valid.Moreover, I am using "application/json" in the header.
I am unable to find a way to fix this error. Here is the JsonRequest.
Here I am trying to use JSONRequest:
public void jsonPOST(String jsonInput) {
RequestQueue queue = Volley.newRequestQueue(getActivity().getApplicationContext());
String URL = "http://Servername:8080/users";
try{
JsonObjectRequest req = new JsonObjectRequest(URL, new JSONObject(jsonInput),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
VolleyLog.v("Response:%n %s", response.toString(4));
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.e("Error: ", error.getMessage());
}
});
queue.add(req);
}
catch (JSONException error){
String output = error.toString();
}
}
I have checked the JSONObject in the debugger and it's valid. I am also checked the network firewall but it also seems fine

Volley Get Request: onResponse is never called

im pretty new to Android Studio and I'm trying to build a Get Request using Volley, the Server response is a JsonObject. I tested the code with breakpoints but I wonder why I don't jump into onResponse or why it won't work.
Here's my Code of the Get Method:
public Account GetJsonObject(String urlExtension, String name, Context context) {
String baseURL = "myurl.com/api";
baseURL += urlExtension + "/" + name;
// url will look like this: myurl.com/api/user/"username"
final Account user = new Account("","");
//Account(name, email)
RequestQueue requestQueue;
requestQueue = Volley.newRequestQueue(context);
JsonObjectRequest jsonObject = new JsonObjectRequest(Request.Method.GET, baseURL,null,
new Response.Listener<JSONObject>() {
// Takes the response from the JSON request
#Override
public void onResponse(JSONObject response) {
try {
JSONObject obj = response.getJSONObject("userObject");
String username = obj.getString("Username");
String email = obj.getString("Email");
user.setUsername(username);
user.setEmail(email);
}
catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue.add(jsonObject);
return user;
}
As #GVillavani82 commented your onErrorResponse() method body is empty. Try to log the error like this
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("ERROR", "Error occurred ", error);
}
}
Make sure that you have the below permission set in AndroidManifest.xml file and the api URL is proper.
<uses-permission android:name="android.permission.INTERNET"/>
And JsonObjectRequest class returns Asynchronous network call class. Modify your code like below.
// remove Account return type and use void
public void GetJsonObject(String urlExtension, String name, Context context) {
....
.... // other stuffs
....
JsonObjectRequest jsonObject = new JsonObjectRequest(Request.Method.GET, baseURL,null,
new Response.Listener<JSONObject>() {
// Takes the response from the JSON request
#Override
public void onResponse(JSONObject response) {
processResponse(response); // call to method
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("ERROR", "Error occurred ", error);
}
});
requestQueue.add(jsonObject);
}
Now create another method like below
private void processResponse(JSONObject response) {
try {
final Account user = new Account("","");
JSONObject obj = response.getJSONObject("userObject");
String username = obj.getString("Username");
String email = obj.getString("Email");
user.setUsername(username);
user.setEmail(email);
} catch (JSONException e) {
e.printStackTrace();
}
}

Using volley to make web service call

I have a web api setup and one of the endpoints in the API takes a JSON object (which in the API gets resolved to a .NET object).
Using Postman I can successfully call the post endpoint, here is the URL
https://example.com/api/helprequests
And here is the JSON which I include in the Postman request
{"Title":"Test Title", "Message":"Test Message"}
Everything works well in Postman, but I am trying to call this API from an Android app using Volley.
Here is the relevant code
String webAddress = "http://example.com/api/helprequests/";
RequestQueue queue = Volley.newRequestQueue(this);
StringRequest stringRequest = new StringRequest(Request.Method.POST, webAddress,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("RESPONSE", response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("RESPONSE", "That didn't work!");
}
}) {
#Override
public String getBodyContentType() {
return "application/json";
}
#Override
public byte[] getBody() throws AuthFailureError {
try {
Map<String, String> params = new HashMap<String, String>();
params.put("Title","Test title");
params.put("Message", "Test message");
} catch (Exception ex) {
VolleyLog.wtf("Unsupported Encoding");
return null;
}
return null;
}
};
queue.add(stringRequest);
When I run this I get the following error:
E/Volley: [50225] BasicNetwork.performRequest: Unexpected response code 500 for https://example.com/api/helprequests
How do I add post data to a Volley request?
Instead of using the StringRequest do use JsonObjectRequest.
String webAddress = "http://example.com/api/helprequests/";
RequestQueue queue = Volley.newRequestQueue(this);
JSONObject object = new JSONObject();
try {
object.put("Title", "my title");
object.put("Message", "my message");
} 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!");
}
});
queue.add(request);
String webAddress = "http://example.com/api/helprequests/";
RequestQueue queue = Volley.newRequestQueue(this);
JSONObject jsonObject= new JSONObject();
try {
jsonObject.put("Title", "my title");
jsonObject.put("Message", "my message");
} catch (JSONException e) {
}
RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
JsonObjectRequestWithHeader jsonObjReq = new JsonObjectRequestWithHeader(Request.Method.POST,
webAddress , jsonObject, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.v("Response0", response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("Response", "Error: " + error.getMessage());
pd.dismiss();
}
});
int socketTimeout = 50000;//30 seconds - change to what you want
RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
jsonObjReq.setRetryPolicy(policy);
queue.add(jsonObjReq);
return null;
}

Send image via JsonObjectRequest Volley in Android?

I have a POST method send a JsonObject via Volley:
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, url, postBody, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
log("success");
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
log("" + error);
}
});
request.setRetryPolicy(new DefaultRetryPolicy(10000, 0, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
Volley.newRequestQueue(this).add(request);
With postBody:
JSONObject postBody = new JSONObject();
try {
postBody.put("name", "rome");
//postBody.put("image", file?);
} catch (JSONException e) {
log("" + e);
}
I want to send a image file with key "image" above. This file type is the same with file of form-data in PostMan (not url of file).
Is there anyway to do it? Thanks.

How to send Json POST request using Volley in android in the Given Tutorial?

Hi I am a beginner in Android , I am learning to make Api Calls. I got a tutorial of Volley which uses GET to Receive response. Now I want to Send Post request Using Volley. I don't know how to do that, what would be the code for POST in the given Tutorial. Please guide me to send Post Request.The link to the tutorial that I am learning is http://www.truiton.com/2015/02/android-volley-example/
you have to used below code to send request
// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(this);
String url ="http://www.google.com";
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Display the first 500 characters of the response string.
mTextView.setText("Response is: "+ response.substring(0,500));
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
mTextView.setText("That didn't work!");
}
});
// Add the request to the RequestQueue.
queue.add(stringRequest);
try {
/** json object parameter**/
JSONObject jsonObject = new JSONObject();
jsonObject.put("hello", "hello");
Log.e("jsonObject params", jsonObject.toString() + "");
/**URL */
String url ="http://google.com"
progress.setVisibility(View.VISIBLE);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url, jsonObject, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject jsonObject) {
progress.setVisibility(View.GONE);
Log.e(TAG, "Response " + jsonObject.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
progress.setVisibility(View.GONE);
Log.e(TAG, volleyError);
Util.showToast(activity, "Please try again");
}
});
requestQueue.add(jsonObjectRequest);
} catch (JSONException e) {
progress.setVisibility(View.GONE);
Log.e(TAG, e);
}
catch (Exception e) {
progress.setVisibility(View.GONE);
Log.e(TAG, e);
}
}
}
RequestQueue queue = Volley.newRequestQueue(this);
queue.add(jsonObjectRequest);
You can follow this :http://www.androidhive.info/2014/05/android-working-with-volley-library-1/
StringRequest request = new StringRequest(Method.POST,
"post url",
new ResponseListener() {
#Override
public void onResponse(String response) {
Log.d("response", response);
} catch (Exception e) {
e.printStackTrace();
}
}
}, new ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("response","error");
}
}) {
// post params
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("param", "param");
return params;
}
};
//2.Use your custom volley manager send request or like this
Volley.newRequestQueue(mCtx).add(request);

Categories

Resources