How to send Body Data to GET Method Request android using volley? - java

I have an API which send me a JSON object when I send a token to the server , I use GET method and I have to send token in body, not headers, it works in postman correctly when I put token in body but I have volley server error in android studio and I entered error response.here is my codes:
ant solution???? please
private void getFreightsFromServer()
{
final String url =" https://parastoo.app/api/driver-cargo-list";
JSONObject jsonData = new JSONObject();
String token = G.getString("token");
try
{
jsonData.put("token", token);
} catch (JSONException e)
{
e.printStackTrace();
}
Response.Listener<JSONObject> listener = new Response.Listener<JSONObject>()
{
boolean isGet = false;
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
public void onResponse(JSONObject response)
{
try
{
MyPost post = new MyPost();
JSONArray jsonArray = response.getJSONArray("results");
for (int i = 0; i < jsonArray.length(); i++)
{
JSONObject tempJsonObject = jsonArray.getJSONObject(i);
JSONObject jsonOriginCustomer = new JSONObject(tempJsonObject.getString("origin_customer"));
post.setOriginCity(jsonOriginCustomer.getString("customerCity"));
JSONObject jsonDestinationCustomer = new JSONObject(tempJsonObject.getString("destination_customer"));
Log.d("result", jsonDestinationCustomer.getString("customerCity"));
post.setDestinationCity(jsonDestinationCustomer.getString("customerCity"));
freightsList.add(post);
// isGet = true;
adapter.notifyDataSetChanged();
}
} catch (JSONException e)
{
e.printStackTrace();
}
}
};
Response.ErrorListener errorListener = new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error)
{
Toast.makeText(getContext(), error.toString(), Toast.LENGTH_LONG).show();
Log.d("jdbvdc", error.toString());
error.printStackTrace();
}
};
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, jsonData, listener, errorListener);
Log.d("fhdhdcf",jsonData.toString());
final int socketTimeout = 100000;
RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, 0, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
request.setRetryPolicy(policy);
AppSingleton.getInstance(getContext()).addToRequestQueue(request);
}

Please show the error message you have. Also I am not sure how ok it is to send something in a body of a GET request. This answer might help you:
HTTP GET with request body

It's better to use post method for this type of request.
But still if you want to use GET method then you should have to pass token in the URL.
Below is an example
final String username = etUname.getText().toString().trim();
final String password = etPass.getText().toString().trim();
URLline = "https://demonuts.com/Demonuts/JsonTest/Tennis/loginGETrequest.php?username="+username+"&password="+password;

Related

Volley Response Issue Android

I'm parsing a simple JSON response, and it is working when trying to parse the employer name, but it gets to a point where it will eventually crash and say that my 'review' json object, is empty. Here is the response:
https://raw.githubusercontent.com/vikrama/feed-json-sample/master/feed.json
And here is how I'm reading it:
private void extractName()
{
RequestQueue queue = Volley.newRequestQueue(this);
JsonObjectRequest request = new JsonObjectRequest(JSON_URL, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONObject gimme = response.getJSONObject("response");
JSONArray resultsArray = gimme.getJSONArray("results");
for(int i = 0; i < resultsArray.length(); i++)
{
JSONObject info = resultsArray.getJSONObject(i);
JSONObject review = info.getJSONObject("review");
Log.d("COMP NAME", review.getString("employerName"));
companyNames.add(review.getString("employerName"));
}
recyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.this));
adapter = new CompanyAdapter(MainActivity.this, companyNames);
recyclerView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("TAG", error.getMessage());
}
});
queue.add(request);
}
The debug line prints the correct values, then abruptly stops saying "no value for review". I'm pretty confused by this because it seems i'm reading through the data correctly. (use https://jsonformatter.org/json-viewer to better format this json i listed above)
Also, everything else in my recyclerview is set up properly, and the method extractName() is being called in the onCreate() method of my main activity.
This is happening because in some JSON Object you don't have "review" object, so it's throwing your code directly to catch Exception.
In order to overcome this, Please use:-
if(info.has("review")) {
JSONObject review = info.getJSONObject("review");
companyNames.add(review.getString("employerName"));
}
Instead of:
JSONObject review = info.getJSONObject("review");
Log.d("COMP NAME", review.getString("employerName"));
companyNames.add(review.getString("employerName"));

JSON RPC response to Array Android

I managed to get results for a json rpc request, like this:
{"id":1,"jsonrpc":"2.0","result":{"channels":[{"channel":"Channel A ","channelid":2165,"label":"Channel A"},{"channel":"Channel B ","channelid":748,"label":"Channel B"} etc.
I would like to parse the reponse to an array where i can read channel,channelid and label at each iteration of a loop. but did not manage to get it.
Any help would be much appreciated.
Sorry not that experienced with programming , its al self-taught
Code for json rpc request :
String groupchannelsurl = "http://192.168.2.100:8080/jsonrpc?request={\"jsonrpc\": \"2.0\", \"method\": \"PVR.GetChannels\", \"params\": {\"channelgroupid\" : 9,\"properties\":[\"channel\"]}, \"id\": 1 }";
RequestQueue queue = Volley.newRequestQueue(this);
JsonObjectRequest getRequest = new JsonObjectRequest(Request.Method.GET, groupchannelsurl, null,
new Response.Listener<JSONObject>()
{
#Override
public void onResponse(JSONObject response) {
// display response
Log.d("Response", response.toString());
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Error.Response", error.toString());
}
}
);
queue.add(getRequest);
The Android Developer documentation is really good if you get stuck.
JSONObject -
https://developer.android.com/reference/org/json/JSONObject.html
JSONArray - https://developer.android.com/reference/org/json/JSONArray.html
#Override
public void onResponse(JSONObject response) {
JSONArray channels = response.getJSONObject("result").getJSONArray("channels");
for (int i = 0; i < channels.length(); i++) {
JSONObject channel = channels.getJSONObject(i);
String channelName = channel.getString("channel");
int channelId = channel.getInt("channelid");
String channelLabel = channel.getString("label");
// ...
}
}
Hope this helps!
You can parse JSONObject like below
private void parseJsonObject(JSONObject responseObject) throws JSONException {
String id = responseObject.getString("id");
JSONArray jsonArray = responseObject.optJSONArray("channels");
if (jsonArray != null) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject arrayObject = (JSONObject) jsonArray.get(i);
String channel = arrayObject.getString("channel");
String channelId = arrayObject.getString("channelid");
}
}
}

How to retrieve JSONObject from JSONArray request using Flickr API?

I want to retrieve comments from a Flickr photo in my Android app, and have created a JSONObjectRequest using the following code:
public void loadComments(ImageInfo photo) {
//clear the comments arraylist ready for new request
NetworkMgr.getInstance(this).commentsList.clear();
NetworkMgr netMgr = NetworkMgr.getInstance(getApplicationContext());
RequestQueue requestQueue = netMgr.requestQueue;
String id = photo.id;
String url = "https://api.flickr.com/services/rest/?method=flickr.photos.comments.getList&api_key=MY_API_KEY&format=json&nojsoncallback=1&extras=authorname,_content&photo_id=" + id;
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, responseListener, errorListener);
requestQueue.add(request);
adapter.notifyDataSetChanged();
}
The photo ID is correctly being retrieved and appended to the String url, and below I use a response listener to get authorname and _content, from each comment object:
private Response.Listener<JSONObject> responseListener = new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONObject comments = response.getJSONObject("comments");
JSONArray commentList = comments.getJSONArray("comment");
for (int i = 0; i < commentList.length(); i++) {
ImageInfo newComment = new ImageInfo();
JSONObject comment = commentList.getJSONObject(i);
newComment.authorname = comment.getString("authorname");
newComment.commentContent = comment.getString("_content");
//add data to arraylist
NetworkMgr.getInstance(DetailsActivity.this).commentsList.add(newComment);
}
} catch (JSONException ex) {
ex.printStackTrace();
}
adapter.notifyDataSetChanged();
}
};
private Response.ErrorListener errorListener = new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
};
However when I put this url in my browser to view the JSON data, the comment JSONObject is non-existent.
How The JSON Response Should Look <<<< How My JSON Response Looks <<<<
Does anybody know why I cannot retrieve the JSON comment object and its data?
Try this
Put this in your loop
JSONObject allvaluesJsonObject=new JSONObject();
allvaluesJsonObject=jsonArray.getJSONObject(i);
remove this ImageInfo newComment = new ImageInfo();

get json that have integer with volley library

i have a problem with get json with volley library.
this is my json:
{"result":1}
the php code count rows in mysql database and show result in this json file.
the number of count is integer.
and this is my code for get this json:
private void getData () {
//url + id of row that want to count
String url = Config.DATA_URL_COUNT +"1";
StringRequest stringRequest = new StringRequest(url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//loading.setVisibility(View.INVISIBLE);
showJSON(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// Toast.makeText(this,error.getMessage().toString(), Toast.LENGTH_LONG).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void showJSON(String response) {
int name = 0;
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray result = jsonObject.getJSONArray(Config.TAG_RESULT);
JSONObject collegeData = result.getJSONObject(0);
name = jsonObject.getInt(Config.JSON_ARRAY);
} catch (JSONException e) {
e.printStackTrace();
}
String count = String.valueOf(name);
rowcount_kargozarybime.setText(count); //insert result in textview
}
and this is my php code:
<?php
if($_SERVER['REQUEST_METHOD']=='GET'){
$categoryid = $_GET['categoryid'];
define('HOST','144.76.10.250');
define('USER','cp21983_test');
define('PASS','*******');
define('DB','cp21983_marivanjobs');
$con = mysqli_connect(HOST,USER,PASS,DB);
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_query($con,"SET character_set_results=utf8,character_set_client=utf8,character_set_connection=utf8, character_set_database=utf8,character_set_server=utf8");
$sql="SELECT * FROM jobs WHERE categoryid='".$categoryid."'";
if ($result=mysqli_query($con,$sql))
{
// Return the number of rows in result set
$rowcount=mysqli_num_rows($result);
echo json_encode(array("result"=>$rowcount));
// Free result set
mysqli_free_result($result);
}
mysqli_close($con);
}
i well be thankfull if anyone can help me.
Try using :
JSONObject respObject = new JSONObject(response);
int result = respObject.getInt("result");
This is a json object,not a json array. therefore use this code to get result count
JSONObject jsonObject = new JSONObject(response);
int count = jsonObject.getInt("result");
rowcount_kargozarybime.setText(String.valueOf(count));

Volley JSONException: End of input at character 0 of

I've seen others come across this problem, but none of the posts have been able to assist me. I'm attempting to use Volley for my REST call library, and when I'm attempting to use a Put call with a JSON Object as a parameter, I'm getting error with: org.json.JSONException: End of input at character 0 of.
Here is the code:
protected void updateClientDeviceStatus(Activity activity, final int status) {
JSONObject jsonParams = new JSONObject();
try {
jsonParams.put("statusId", String.valueOf(status));
} catch (JSONException e1) {
e1.printStackTrace();
}
Log.i(LOG_TAG, "json: " + jsonParams.toString());
String url = Constants.API_URL + "client/device/" + getDeviceId();
// Request a response from the provided URL.
JsonObjectRequest request = new JsonObjectRequest
(Request.Method.PUT, url, jsonParams, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.i(LOG_TAG, "updated client status");
Log.i(LOG_TAG, "response: " + response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.i(LOG_TAG, "error with: " + error.getMessage());
if (error.networkResponse != null)
Log.i(LOG_TAG, "status code: " + error.networkResponse.statusCode);
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("User-Agent", getUserAgent());
params.put("X-BC-API", getKey());
return params;
}
#Override
public String getBodyContentType() {
return "application/json";
}
};
request.setRetryPolicy(new DefaultRetryPolicy(20000, 3, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
MySingleton.getInstance(activity).addToRequestQueue(request);
}
}
The jsonParams log displays:
json: {"statusId":"1"}
Is there another setting that I'm missing? It appears that the request can't parse the JSON Object. I even tried creating a HashMap and then using that to create a JSON Object, but I still get the same result.
I also have encountered this issue.
It's not necessarily true that this is because a problem on your server side - it simply means that the response of the JsonObjectRequest is empty.
It could very well be that the server should be sending you content, and the fact that its response is empty is a bug. If, however, this is how the server is supposed to behave, then to solve this issue, you will need to change how JsonObjectRequest parses its response, meaning creating a subclass of JsonObjectRequest, and overriding the parseNetworkResponse to the example below.
#Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
try {
String jsonString = new String(response.data,
HttpHeaderParser.parseCharset(response.headers, PROTOCOL_CHARSET));
JSONObject result = null;
if (jsonString != null && jsonString.length() > 0)
result = new JSONObject(jsonString);
return Response.success(result,
HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JSONException je) {
return Response.error(new ParseError(je));
}
}
Keep in mind that with this fix, and in the event of an empty response from the server, the request callback will return a null reference in place of the JSONObject.
Might not make sense but nothing else worked for me but adding a content-type header
mHeaders.put("Content-Type", "application/json");
In my case it was simply the request I was sending(POST) was not correct. I cross-checked my fields and noted that there was a mismatch, which the server was expecting to get thus the error->end of input at character 0 of...
I had the same problem, I fixed it by creating a custom JsonObjectRequest that can catch a null or empty response :
public class CustomJsonObjectRequest extends JsonObjectRequest {
public CustomJsonObjectRequest(int method, String url, JSONObject jsonRequest, Response.Listener<JSONObject> listener, Response.ErrorListener errorListener) {
super(method, url, jsonRequest, listener, errorListener);
}
public CustomJsonObjectRequest(String url, JSONObject jsonRequest, Response.Listener<JSONObject> listener, Response.ErrorListener errorListener) {
super(url, jsonRequest, listener, errorListener);
}
#Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
try {
String jsonString = new String(response.data,
HttpHeaderParser.parseCharset(response.headers));
JSONObject result = null;
if (jsonString != null && jsonString.length() > 0)
result = new JSONObject(jsonString);
return Response.success(result,
HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JSONException je) {
return Response.error(new ParseError(je));
}
}
Then just replace the default JsonObjectRequest by this one !
You need to check if the server response is not empty. Maybe it could be a emtply String "".
if (response.success()) {
if (response.getData() == null) {
return null;
} else if (response.getData().length() <= 0){
return null;
}
// Do Processing
try {
I have faced the same problem, there was just a small silly mistake that happened.
instead of
val jsonObject = JSONObject(response.body()?.string())
should be
val jsonObject = JSONObject(response.body()!!.string())

Categories