Android Volley POST Json to Server - android

I am using Volley to transfer the data between Android device and web server.
I found a issue about sending a list of data to the server.
For example, my class will generate the data set like this:
{
"1": {
"1_aID": "5",
"2_aID": "5",
"3_aID": "5",
"4_aID": "5"
},
"2": {
"1_bID": "3",
"2_bID": "3",
"3_bID": "3"
},
"3": {
"1_cID": "4"
}
}
How can i send those data to Server?
I found some tutorial of Post data to server. It must using hashmap.
Any better solution to handle this case?

Make a volley request like bellow which takes method like POST/GET,
url, response & error listener. And For sending your json override
getBody() method in which pass the json you want to send.
Make a RequestQueue & add the request to it. You might start it by
calling start()
Try this :
// 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) {
// your response
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// error
}
}){
#Override
public byte[] getBody() throws AuthFailureError {
String your_string_json = ; // put your json
return your_string_json.getBytes();
}
};
// Add the request to the RequestQueue.
queue.add(stringRequest);
requestQueue.start();
For more info see this

Try this
JSONObject rootObj = new JSONObject();
JSONObject oneObject = new JSONObject();
oneObject.put("1_aID","5");
...
...
JSONObject threeObject = new JSONObject();
oneObject.put("1_cID","4");
rootObj("1",oneObject);
...
...
rootObj("3",threeObject);
new JsonObjectRequest(Request.Method.POST,
url,
rootObj.toString(),
responselistner,
errorlistner);

Related

Android Volley Multidimensional JSON Request post Method

How to send multidimensional array on volley post method.
{
"code": "001",
"Emp_id": "0000",
"Exp_Dt": "2021-05-27T00:00:00.000",
"users": [
{
"id": "1087",
"name": "Abhishek Saini",
"email": "info#ezacake.com",
"gender" : "male"
},
{
"id": "1088",
"name": "Gourav",
"email": "gourav9188#gmail.com",
"gender" : "male"
}
]
}
This format I want to call API. Please help
Note - I want to Request with array on my API, not a response
hi you are trying to send a json object there =>
create a parent json object
JSONObject reqJO = new JSONObject();
put other properties eg
reqJo.put("code",0001);
create a user json object
JSONObject user = new JSONObject();
put user properties(if more users loop creating new users)eg
user.put("id",1087)
create a json array of users
JSONArray users = new JSONArray();
add user in users array
users.put(user);
put users array in parent object
reqJO.put("users",users);
Then you continue with your JsonObjectRequest
Here is the answer
RequestQueue queue = Volley.newRequestQueue(this);
JsonObjectRequest jobReq = new JsonObjectRequest(Request.Method.POST, url, jObject,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject jsonObject) {
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
}
});
queue.add(jobReq);

Why Volley response is received as "[" and not JSON

I am learning about Volley and I don't know why the response from GET method is coming as a single char -> [.
I am using this method to get the JSON response:
public void getJsonMethod() {
// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(context);
// String url = "https://www.w3schools.com/js/myTutorials.txt";
String url = "http://www.google.com"; // with this url I am getting response
// Request a string response from the provided URL.
final StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
System.out.println("Response is: " + response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println("Response is not good" + error.getMessage());
}
});
// Add the request to the RequestQueue.
queue.add(stringRequest);
}
When I am using this link I do get a response but when I try to use some link that contains nothing but JSON like this one my response it "[".
I am calling this method from Activity like this:
GetJsonClass getJson = new GetJsonClass(this);
getJson.getJsonMethod();
Any ideas on what am I doing wrong here?
Answer + code
If anyone will start using Volley maybe this can help him :
as David Lacroix said in his answer, I called stringRequest and notJsonArrayRequest.
Here is how it should have been:
public void getJsonMethod() {
// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(context);
String url = "your url";
JsonArrayRequest jsonObjectRequest = new JsonArrayRequest(url, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
System.out.println("this is response good" + response);
}
}, new ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println("this is response bad" + error);
}
});
queue.add(jsonObjectRequest);
}
See https://developer.android.com/training/volley/request
StringRequest. Specify a URL and receive a raw string in response. See Setting Up a Request Queue for an example.
JsonObjectRequest and JsonArrayRequest (both subclasses of JsonRequest). Specify a URL and get a JSON object or array (respectively) in response.
You should be using a JsonArrayRequest
myTutorials.txt is being served with status code 304 (no proper suffix and MIME type either):
304 Not Modified. If the client has performed a conditional GET request and access is allowed, but the document has not been modified, the server SHOULD respond with this status code. The 304 response MUST NOT contain a message-body, and thus is always terminated by the first empty line after the header fields.
In other terms, what the browser may display is not neccessarily the same what the server has sent. eg. GSON would accept that JSON only with option lenient enabled, because the array has no name.
see RFC 2616.

Getting ''org.json.JSONArray cannot be converted to JSONObject''

I'm trying to get data from my server in json format in my android application using volley library post json method. But everytime gets a 'org.json.JSONArray cannot be converted to JSONObject'.
This the error:
Error: org.json.JSONException: Value [{"status":"Success","code":1313,"msg":"Request completed successfully"}] of type org.json.JSONArray cannot be converted to JSONObject.
And that's my code:
RequestQueue requestQueue = Volley.newRequestQueue(this);
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("auth", "---------");
jsonObject.put("request", "Login");
jsonObject.put("Name", "raky");
jsonObject.put("Email", "exp#a.com");
} catch (JSONException e) {
e.printStackTrace();
}
String url = "http://my.website_name.com/";
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url, jsonObject,
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("ERROR.VOLLEY", error.getMessage());
}
});
jsonObjectRequest.setTag(1);
requestQueue.add(jsonObjectRequest);
The prolem here is that your website response body object is a JSONArray
[
{
"status": "Success",
"code": 1313,
"msg": "Request completed successfully"
}
]
So you get the exception because in the response handler you want a JSONObject and you can't cast a JSONArray to a JSONObject.
What your server (website) have to return to you is a root JSONObject and then in its node tree it could have JSONArray, but the root must be a JSONObject.
So fix your server side code so that it returns:
{
"status": "Success",
"code": 1313,
"msg": "Request completed successfully"
}
Your response is an Array,
you can test your api with some api test tools like Postman and see what you get from api, also you can use StringRequest instead of JsonObjectRequest, by this method you can get any type of response and converted to the type you need

Parse url with curly brackets in Android App

How can i Parse url with curly brackets like
http://example.com/api/login/{username}/{password} in an android application.
Normal volley post request returns html.But i need JSON.
Integrating Login API in Android App
If I get you right, what you want to do is send a GET request for login.
The following code can help you (it is not recommended to use GET for login, use POST instead. I'm giving a GET ex because that's what your'e asking for):
final TextView mTextView = (TextView) findViewById(R.id.text);
// ...
// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(this);
String url ="http://example.com/api/login/your_username/your_password";
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, 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!");
}
});

Send data to server as json format using android Volley

I want to send data from android app to remote server in JSON format.
Below is my json format :-
{
"contacts": [
{
"name": "ritva",
"phone_no": "12345657890",
"user_id": "1"
},
{
"name": "jisa",
"phone_no": "12345657890",
"user_id": "1"
},
{
"name": "tithi",
"phone_no": "12345657890",
"user_id": "1"
}
]
}
Can any one tell me how do I send this data using Volley?
Make a volley request like bellow which takes method like POST/GET,
url, response & error listener. And For sending your json override
getBody() method in which pass the json you want to send.
Make a RequestQueue & add the request to it. You might start it by
calling start()
Try this :
// 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) {
// your response
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// error
}
}){
#Override
public byte[] getBody() throws AuthFailureError {
String your_string_json = ; // put your json
return your_string_json.getBytes();
}
};
// Add the request to the RequestQueue.
queue.add(stringRequest);
requestQueue.start();
For more info see this
1. Add Volley and Gson Dependency into build.gradle:
'com.mcxiaoke.volley:library:1.0.19'
'com.google.code.gson:gson:2.7'
Note: If you have JSON data in String variable then just pass the String variable as third parameter in JsonObjectRequest.(Go to Step 6)
If you have JSON data in your classes then just pass the class in gson.toJson() of the third parameter of JsonObjectRequest.(Go to Step 6)
If you want to get the data in class then you need to create classes structure same as JSON data. (Go to step 2)
2. Then create the POJO classes for the above JSON Structure using http://www.jsonschema2pojo.org/
Example Shown in image:
Red marks showing the changes needed to make on site
Then you will get two classes as ContactsTop and Contact.
Note: ContactsTop is name provided at the time of creating POJO classes from jsonschema2pojo.com
3. Add above generated classes into your project
4. Create Volley RequestQueue object and gson object.
RequestQueue requestQueue = Volley.newRequestQueue(this);
Gson gson = new Gson();
5. Then add above JSON data to POJO Classes.
ContactsTop contactsTop=new ContactsTop();
List<Contact> contactList =new ArrayList();
Contact contact=new Contact();
contact.setPhoneNo("12345657890");
contact.setName("ritva");
contact.setUserId("1");
contactList.add(contact);
contactsTop.setContacts(contactList);
6. Create JSONObject to call web service with your data.
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, "www.your-web-service-url.com/sendContact.php", gson.toJson(contactsTop), new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.v("Volley:Response ", ""+response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.v("Volley:ERROR ", error.getMessage().toString());
}
});
7. Add your jsonObjectRequest into requestQueue. (Don't forget to add this line. this is will add your request in RequestQueue and then only you will get JSON Response or Error from your Service). Don't forget to add INTERNET Permission in AndroidManifest.xml
requestQueue.add(jsonObjectRequest);
Then you will get Response or Error from your Remote Service in android Log monitor.
For sending JSON type data you should make a JSON request using volley
// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(this);
String url ="http://www.google.com";
JsonObjectRequest jsObjRequest = new JsonObjectRequest
(Request.Method.POST, url, obj, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO Auto-generated method stub
}
});
// Add the request to the RequestQueue.
queue.add(stringRequest);
requestQueue.start();
Where object is your JSONObject that you want to send. Ask if you want more clarification.
Mark this up if this helps you.

Categories

Resources