I'm trying to retrieve a jsonarray from a url using Volley.
the problem is that I get
JsonException end of input at character 0
the code is the following:
JsonArrayRequest req = new JsonArrayRequest(Request.Method.POST, openMatchesUrl,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d("JSON", response.toString());
try {
for (int i = 0; i < response.length(); i++) {
//do stuff
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(),
"onErrorResponse ongoing: "+error.getMessage(), Toast.LENGTH_SHORT).show();
}
}){
#Override
protected Map<String, String> getParams()
{
//build params
}
};
// Add the request to the RequestQueue.
queue.add(req);
I was thinking that the problem was in wrong parameters. but I tried with a simple string request:
StringRequest req = new StringRequest(Request.Method.POST, openMatchesUrl,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("JSON", "resp: " +response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("JSON", error.toString());
}
}){
#Override
protected Map<String, String> getParams()
{
//build params
}
};
and it's actually returning the json correctly. for example:
[{"roundid":4152,"numberofplayers":1,"dateevent":"2015-04-13 19:45:32.121124+02","playernames":"cat","turn":1,"codedboard":""},{"roundid":4154,"numberofplayers":1,"dateevent":"2015-04-13 20:16:08.845409+02","playernames":"cat","turn":1,"codedboard":""},{"roundid":4155,"numberofplayers":1,"dateevent":"2015-04-13 20:18:22.002411+02","playernames":"cat","turn":1,"codedboard":""}]
what's the problem here?
Total shot in the dark, but I had similar occur on an RSS parser. It turns out the URL I was using was HTTP, but redirected to HTTPS and I was using an HttpURLConnection instead of HttpsURLConnection.
Though, I wasn't using Android Volley so YMMV.
I finally solved this, the problem here is that for some reason JSonArrayRequest was not taking the POST parameters.
So I just manually appended the parameters to the url
Related
I am using Volley for networking and connect to my REST API. The following code shows the onCreate method of my MainActivity. Here I want to make a GET request to my url and receive the JSON information. But it's not working. I made different debug points all over the code. The last thing which is executed is the initialization of the arrReq. onResponse and onErrorResponse are not executed and I don't know what is the matter.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setupToolBar();
setupPagerAdapter();
setupFloatingButton();
getDeviceId();
JsonArrayRequest arrReq = new JsonArrayRequest(com.android.volley.Request.Method.GET, "http://localhost:8888/api/entities", null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
// Check the length of our response (to see if there are any entities)
if (response.length() > 0) {
// There are entities so let's loop through them all.
for (int i = 0; i < response.length(); i++) {
try {
// Get each entity
JSONObject jsonObj = response.getJSONObject(i);
String locData = jsonObj.get("entity").toString();
} catch (JSONException e) {
// If there is an error then output this to the logs.
Log.e("Volley", "Invalid JSON Object.");
}
}
} else {
// There aren't any entities. So do nothing!
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// If there a HTTP error then add a note to our list.
Log.e("Volley", error.toString());
}
}
);
}
When I execute the url in my browser on my device the JSON code is received:
{
"status":"success",
"data":[
{
"entity":"(17,)"
},
{
"entity":"(21,)"
},
{
"entity":"(201,)"
}
],
"message":"Retrieved entities"
}
The log does not show any error.
JsonArrayRequest request = new JsonArrayRequest (Request.Method.GET, URL, new Response.Listener<String>() {
#Override
public void onResponse(JSONArray response) {
if (!response.equals(null)) {
Log.e("Your Array Response", response);
} else {
Log.e("Your Array Response", "Data Null");
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("error is ", "" + error);
}
}) {
//This is for Headers If You Needed
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
//Map<String, String> params = new HashMap<String, String>();
// params.put("Content-Type", "application/json; charset=UTF-8");
// params.put("Authorization", "bearer " + token);
return params;
}
//Pass Your Parameters here
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
/*params.put("User", UserName);
params.put("Pass", PassWord);*/
return params;
}
};
RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
queue.add(request);
Try this one
It might be a permission issue,
did you add your manifest.xml file the following code:
<uses-permission android:name="android.permission.INTERNET" />
Finally I got it. The problem was that I get a JSONObject as response but instanciated a JSONArrayRequest. When I change that into a JSONObjectRequest it works perfectly.
I have this Login Java code in my Android Studio:
private void loginUser(){
pd = ProgressDialog.show(LoginActivity.this, "", "Loading...");
StringRequest stringRequest = new StringRequest(Request.Method.POST, LOGIN_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
System.out.println("JSON RESPONSE: " + jsonResponse.toString());
boolean success = jsonResponse.getBoolean("success");
if (success) {
launchHomeScreen();
pd.dismiss();
Toast.makeText(LoginActivity.this,"Welcome back " + username,Toast.LENGTH_LONG).show();
SharedPreferences sharedPref = getSharedPreferences("loginDatas", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("username", username);
editor.putString("password", password);
editor.apply();
}
else {
loginButton.setBackgroundColor(0x73000000);
Toast.makeText(LoginActivity.this,"Wrong Username or Password!",Toast.LENGTH_LONG).show();
pd.dismiss();
}
}
catch (JSONException e) {
loginButton.setBackgroundColor(0x73000000);
e.printStackTrace();
pd.dismiss();
Toast.makeText(LoginActivity.this,response,Toast.LENGTH_LONG).show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
loginButton.setBackgroundColor(0x73000000);
pd.dismiss();
System.out.println("Error: " + error);
}
}){
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<>();
params.put(KEY_USERNAME,username);
params.put(KEY_PASSWORD,password);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
But everytime I get this error in my Android Log console:
I tried so many things but everytime I try it, I get back: 04-20 07:44:18.463 3326-2366/com.lolol.gg E/Volley: [294] BasicNetwork.performRequest: Unexpected response code 500 for http://lollipop.xyz/login.php
04-20 07:44:18.514 3326-3326/com.lolol.ggI/System.out: Error: com.android.volley.ServerError
Has anybody an Idea, how to fix my problem? Because I tried many things...It won't work anyway...
The weired thing is:
I have tested the server code very often it works. When I try the javacode with the url for my localwampserver it works....When I try it with the url from my hostinger server it didn't work...In the 2 servers are the same codes...
Getting an HTTP response code of 500 means that your app successfully contacted the server, but the server itself has encountered an unexpected error.
Contact your backend maintainer to see why the server is misbehaving, this most probably isn't an issue you can fix in your Android code.
Looks like a server side error, first make sure your service work (using Postman for instance or any rest client).
If the problem persists you could try using Retrofit2 instead of Volley (which I personally prefer)
I have used stringrequest to get response from the server and pass your params.
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {JSONObject jsonObject = new JSONObject(response);
} catch (JSONException ignored) {
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
if (volleyError instanceof TimeoutError) {
}
}
}) {
#Override
public Map<String, String> getParams() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<>();
headers.put("name", "Droider");
return headers;
}
#Override
public Priority getPriority() {
return Priority.IMMEDIATE;
}
};
ApplicationController.getInstance().addToRequestQueue(stringRequest);
I am developing an Android app for a Company. While working on the API the company guys gave me a login API something like this
"app.abc.com/Login?data={"email":"abc","pwd":"123"} "
I am using volley library but I don't know how to post data like this since I have not done it before.
I need advice and wanted to know if this is the right way.
Instead of volley ..try to use android networking library
--to do this :add
--compile 'com.amitshekhar.android:android-networking:0.4.0'
to your gradle file.enter code here
AndroidNetworking.post("your login URL")
.setTag("Login")
.addBodyParameter("email", "abc")
.addBodyParameter("pwd", "123")
.setPriority(Priority.IMMEDIATE)
.build()
.getAsJSONObject(new JSONObjectRequestListener() {
#Override
public void onResponse(JSONObject response) {
try {
JSONObject dataJson = response.getJSONObject("data");
boolean status = dataJson.getBoolean("success");
} else {
JSONArray errorJsonArray = dataJson.getJSONArray("errors");
String errorMsg;
for (int i = 0; i < errorJsonArray.length(); i++) {
errorMsg = errorJsonArray.get(i).toString();
Toast.makeText(LoginActivity.this, errorMsg, Toast.LENGTH_SHORT).show();
}
Log.e("Error", response.toString());
}
} catch (JSONException je) {
je.printStackTrace();
}
}
#Override
public void onError(ANError anError) {
try {
if (anError.getErrorBody() != null) {
JSONObject jsonObject = new JSONObject(anError.getErrorBody());
JSONObject dataJsonObject = jsonObject.getJSONObject("data");
Toast.makeText(getApplicationContext(), dataJsonObject.getString("message"), Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), anError.getErrorDetail(), Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
e.printStackTrace();
}
Log.e("Error", anError.getErrorDetail());
}
});
Using Volley - Create the request queue
RequestQueue queue = Volley.newRequestQueue(this); // this = context
Then create the postRequest, should look somthing like (using Volley):
url = "app.abc.com/Login";
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", response);
}
}
) {
#Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<String, String>();
params.put("data", "{\"email\":\"abc\",\"pwd\":\"123\"}");
return params;
}
};
queue.add(postRequest);
I also recommend using Retrofit and GSON libraries (a bit learning curve here but it is worth it since they are very powerful libraries)
I'm trying to send JSON parameter but server is receiving them as nulls values,
i tried to request it from Postman and it works perfect, i don't know what the problem is with volley i followed the instructions here but it didn't make sense
here is my code
String url = "http://10.10.10.166:8080/SystemManagement/api/Profile/Login";
JSONObject jsonObject=new JSONObject();
try {
jsonObject.put("user_id","Test user name");
jsonObject.put("user_password","test password");
} catch (JSONException e) {
e.printStackTrace();
}
System.out.println(jsonObject.toString());
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest( Request.Method.POST, url, jsonObject,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Toast.makeText(Login.this, response.toString(),Toast.LENGTH_SHORT).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println(error.toString());
}
});
//add request to queue
queue.add(jsonObjectRequest);
I faced same problem, solved by overriding the getParams() method
Here is my login request using Volley.
private void loginRequeset() {
showpDialog();
StringRequest jsonObjReq = new StringRequest(Request.Method.POST, Constants.LOGIN_URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(Login.this, response.toString(),Toast.LENGTH_SHORT).show();
hidepDialog();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
// hide the progress dialog
hidepDialog();
}
})
{
#Override
protected Map<String, String> getParams() {
Map<String, String> signup_param = new HashMap<String, String>();
signup_param.put(Constants.USERNAME, _emailText.getText().toString().trim());
signup_param.put(Constants.PASSWORD, _passwordText.getText().toString().trim());
return signup_param;
}
};
// Adding request to request queue
queue.getInstance().addToRequestQueue(jsonObjReq);
}
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);