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.
Related
My Restful API expect a list of integer arrays. The API works fine when I use postman client to send an json array like so [1,3,4].
I am using android volley to make requests. I have a list of integers which I want to send to the API like this.
//converting integer array to a json array
JSONArray myIntegerJsonArray = new JSONArray(myIntegerArray);
String url = "myurl...";
JsonArrayRequest request = new JsonArrayRequest(Request.Method.GET, url, myIntegerJsonArray, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
//... do stuff here
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
MySingletonRequestQueue.getInstance(this).addToRequestQueue(request);
I am currently getting HttpMessageNotReadableException: Required request body is missing error. So I am guessing it's not sending the myIntegerJsonArray for some reason. What am I doing wrong?
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.
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!");
}
});
(Sorry for any english mistake its not my native language)
I'm trying to parse html using Volley and Jsoup.
while debugging / running the app, the StringRequest dosent invoke onResponse() or onErrorResponse(), basically there no response or Error from the Response.Listener (i guess).
so i cant "begin" parsing the html because the onResponse() is never invoked.
Ive searched for answer and nothing seems to get it fixed.
Could it be that the RequestQueue cache kicks in and its not trying to get the response? (just brain storming tried so many things).
--Im just trying to retrive data from html, so i could show the updated data from the url in my app, is Volly the way or should i use simpler mathods?
here is my volley StringRequest and RequestQueue:
String url = "http://www.fringeb7.co.il/";
final RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);
// 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) {
response_utf8 = URLDecoder.decode(URLEncoder.encode(response, "iso8859-1"),"UTF-8");
doc = Jsoup.parse(response_utf8);
Log.d("logr=",response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
Log.d("log2=", error.toString());
requestQueue.stop();
}
});
// Add the request to the RequestQueue.
requestQueue.add(stringRequest);
took me long enough, but there was no problem.
the code works, while debugging there were no response,
but when i run the app the request complete and i got the wanted response.
so if anyone have a similier problem, from some reason while debugging I dident get response but while running the app its working fine.
(simpley dident know that)
try this first before wasting time in debugging like i did.
If you use Jsoup, you can get it and parse in very simple way:
Document doc = Jsoup.connect("http://www.fringeb7.co.il/").get();
If you still want to use Volley, below code works perfectly in my device:
String url = "http://www.fringeb7.co.il/";
RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);
// 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) {
try {
String response_utf8 = URLDecoder.decode(URLEncoder.encode(response, "iso8859-1"), "UTF-8");
Document doc = Jsoup.parse(response_utf8);
Log.d("logr=", "title = " + doc.title());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
Log.d("log2=", error.toString());
//requestQueue.stop();
}
});
// Add the request to the RequestQueue.
requestQueue.add(stringRequest);
requestQueue.start();
Output of the above code:
D/logr=: title = תיאטרון הפרינג' באר שבע
try 'https' instead of 'http' in your url
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);