How to send Body Data to GET Method Request android - android

like this, I want to send json body request to GET API
tried this but not worked
public static void getQuestionsListApi2(final String requestId, final String timestamp,
final ImageProcessingCallback.downloadQuestionsCallbacks callback,
final Context context) {
try {
String url = NetUrls.downloadQuestions;
final JSONObject jsonBody = new JSONObject();
jsonBody.put("requestId", requestId);
jsonBody.put("timestamp", timestamp);
final String mRequestBody = jsonBody.toString();
Log.i("params", String.valueOf(jsonBody));
Log.i("URL", url);
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, **jsonBody**, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject jsonObject) {
Log.v("TAG", "Success " + jsonObject);
callback.downloadQuestionsCallbacksSuccess(jsonObject.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Log.v("TAG", "ERROR " + volleyError.toString());
}
});
request.setRetryPolicy(new DefaultRetryPolicy(
DefaultRetryPolicy.DEFAULT_TIMEOUT_MS * 0,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
RequestQueue queue = Volley.newRequestQueue(context);
queue.add(request);
} catch (JSONException e) {
e.printStackTrace();
}
}
request.setRetryPolicy(new DefaultRetryPolicy(
DefaultRetryPolicy.DEFAULT_TIMEOUT_MS * 0,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
RequestQueue queue = Volley.newRequestQueue(context);
queue.add(request);
Here Is the Code that i am using when sending JSONRequest with GET Method i am getting 400 error response from server and server not except the the data in the url form . I am sending The jsonBody object as parameter. any solution.

If you want to pass Json data in body of GET request, you have to use Query annotation
Call<YourNodelClass> getSomeDetails(#Query("threaded") String threaded, #Query("limit") int limit);
this will pass as Json object {"threaded": "val", "limit": 3}.
i have tried and this one is only working code.

You can use retrofit to send request with body. http://square.github.io/retrofit/
It is easy to use library, example:
#GET("[url node]")
Single<Response<ResponseBody>> doSmt(#Header("Authorization") String token, #Body ListRequest name);
Also, take a look here about get methods with body
HTTP GET with request body
UPDATE
GET method with request body is optional here. However, this RFC7231 document says,
sending a payload body on a GET request might cause some existing
implementations to reject the request.
which means this isn't recommended. Use POST method to use request body.
Check this table from wikipedia.

Related

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.

Android Volley JsonObjectRequest format: http://localhost:8080/xy?param1=1&param2=2

I'm trying to make a Volley JsonObjectRequest (GET) sending Parameters in the following format:
http://localhost:8080/xy?param1=1&param2=2
My Problem is, I should get a Response-Code 200 (OK), if param1 is "1" and param2 is "2". But I always get the wrong Response Code.
So I think, the request is sending in the wrong format.
Map<String, String> params = new HashMap();
params.put("param1", "1");
params.put("param2", "2");
JsonObjectRequest jsObjRequest = new JsonObjectRequest
(Request.Method.GET, "http://localhost:8080/xy", new JSONObject(params), new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO Auto-generated method stub
}
});
// Access the RequestQueue through your singleton class.
QueueSingleton.getInstance(LoginActivity.this).addToRequestQueue(jsObjRequest);
Thanks!
Right now, you're providing your JsonObject(params) as the body of the request, which is incorrect. I don't think Volley will append your provided JSON object to your URL for you on a GET request...so you need to do that yourself.
Get rid of adding the post body, and append the params manually on the URL using Uri.Builder.appendQueryParameter(key, value).
Because you use GET method, try to append the params with the url like
int param1Value = 1, param2Value = 2;
String url = "http://localhost:8080/xy?param1=" + param1Value + "&param2=" + param2Value;
int p1=1;
int p2= 2;
string url= "http://localhost:8080/xy?param1="+p1+"&param2="+p2;
put this url insted of url you are using..

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.

Volley Server Error with null Network response

Every time I try to use POST method with Volley, I get sever error. I get null value in getCause, and some default value in getNetworkResponse.toString().
If I use GET method, this works fine (I get response from my url).
Can anybody help what can I do?
Map<String, String> jsonParams = new HashMap<String, String>();
jsonParams.put("teststr", "abd");
RequestQueue requestQueue = VolleySingleton.getInstance().getRequestQueue();
JsonObjectRequest request = new JsonObjectRequest(
Request.Method.POST,
url,
new JSONObject(jsonParams),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
Toast.makeText(getApplicationContext(), "Success"+response.toString(), Toast.LENGTH_LONG).show();
}catch(Exception e){
Toast.makeText(getApplicationContext(), "JSON ERROR", Toast.LENGTH_LONG).show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("abd", "Error: " + error
+ ">>" + error.networkResponse.statusCode
+ ">>" + error.networkResponse.data
+ ">>" + error.getCause()
+ ">>" + error.getMessage());
}
}) {
#Override
protected Map<String,String> getParams() {
HashMap<String, String> params = new HashMap<String, String>();
params.put("key", "value");
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json; charset=utf-8");
return headers;
}
};
requestQueue.add(request);
Error Log:
Error:
Error: com.android.volley.ServerError>>404>>[B#42b1e0d0>>null>>null
UPDATE:
networkResponse.statusCode comes as 404, though the url is accessible (and return data if I just use GET method). If I remove header part in POST method, still the same.
the url:
<?php
$response = array();
$jsonString = file_get_contents('php://input');
$jsonObj = json_decode($jsonString, true);
if(!isset($jsonObj['teststr'])){
$response["msg"] = "No data.";
}else{
$response["msg"] = "Success: ".$jsonObj['teststr'];
}
echo json_encode($response);
?>
problem is your Queue.
change your volley code to this:
RequestQueue queue = Volley.newRequestQueue(this);
String URL = EndPoints.BASE_URL + "/call";
StringRequest request = new StringRequest(Request.Method.POST, URL,
new Response.Listener<String>()
{
#Override
public void onResponse(String response) {
Log.d("onResponse", response);
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
NetworkResponse response = error.networkResponse;
String errorMsg = "";
if(response != null && response.data != null){
String errorString = new String(response.data);
Log.i("log error", errorString);
}
}
}
) {
#Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<String, String>();
params.put("key_1","value_1");
params.put("key_2", "value_2");
Log.i("sending ", params.toString());
return params;
}
};
// Add the realibility on the connection.
request.setRetryPolicy(new DefaultRetryPolicy(10000, 1, 1.0f));
// Start the request immediately
queue.add(request);
and your php (laravel) code to this:
$response['success'] = true;
$response['user']['tell'] = $user->tell;
$response['user']['code'] = $user->code;
$response['user']['time'] = $time;
$response['user']['register_state'] = '1'
return response()->json($response, 200);
First, try to make sure your server works well.
You can use Postman(chrome plug-in) or any other way to send a post request to the url and see what it responses.
After make sure there's no problem with your server, let us solve the problem with volley.
There's some problem with JsonObjectRequest when you use POST method.
like this Volley JsonObjectRequest Post request not working.
I suggest you use StringRequest first and overwrite the getParams method like you did before. After you survive this task, you can try to write your own request, not very difficult but very useful.
I also suggest add request.setShouldCache(false) before requestQueue.add(request);. By default, volley saves the response in its cache and this behavior may cause some strange problem.
Well,I think you can first print the responseCode in your logcat
Add this code before add to queue
request.setRetryPolicy(new DefaultRetryPolicy(0, -1,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
sometimes, request is timeout before your php executed completely. so try this code. maybe can help
maybe it's related to your operator...
I have the same issue sending JasonObject with Volley.
I tested my app on 9-10 devices with two different operators.
The request on one operator returns an Error with everything null or blank data in it, on the other one everything works fine and I get my Response from API successfully.
I have no idea what do operators do that causes this problem...
Maybe they use some kind of firewall that blocks sending JsonObject.
I tried to display the response as a String and the error went off.
Use response.toString() wherever you want to display the error or use it.
In my case, the answer is retry policy setting.
I put 30 seconds the timeout value, it should be 30000, not 30.
try to increase timeout. i had the same issue and the request timeout was the problem.

consume Asp.net MVC api from android volley

i am trying to consume a MVC 4 api from my android application
i am using Volley library and it work fine to get data from server
the problem is when i try to send data to the web service which i understand it should be done by using post Method and JsonObjectRequest
my method in MVC Api is :
public class ItemController : ApiController
{
public IEnumerable<string> Post(List<string> val)
{
return val;
}
}
and for volley :
String tag_string_req = "req_login";
Map<String, String> params = new HashMap<>();
params.put("email", "S#b.Com");
params.put("username", "basheq");
JsonObjectRequest req = new JsonObjectRequest(Method.POST ,
AppConfig.URL_REGISTER, new JSONObject(params),new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject jsonObject) {
Log.d(TAG, "Login Response: " + jsonObject.toString());
}
}
, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Login Error: " + error.getMessage());
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(req, tag_string_req);
but i keep getting null in response and it look like the api doesn't parse the parameter .
what is wrong ?? , and is this the proper way to do it or is there a better way ??
The main problem was that i was setting list as a parameter which for some reason does not work
the solution was by wrapping the input parameter into a class and of course change the json structure to correspond to that

Categories

Resources