HTTP request via Volley to ByteHost - java

Recently i had asked about an alternative for HTTPClient class in java.
the best alternative was Android Volley SDK.
I compiled it in my Android project. and wrote the appropriate code.
but i received an error.
com.android.volley.ParseError: org.json.JSONException
I'm using ByteHost PHP code as JSON provider.
Here is the PHP code:
<?php
mysql_connect("###","###","###");
mysql_select_db("###");
$sql1=mysql_query("SELECT * FROM coords;");
if (!$sql1) {
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit();
}
while($row=mysql_fetch_assoc($sql1))
$output[]=$row;
print(json_encode(array('bus' => $output)));
mysql_close();
exit();
?>
PLUS the Java code:
rq = Volley.newRequestQueue(this);
String url = "http://www.justbusesdbs.eb2a.com";
JsonObjectRequest r = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray JA = response.getJSONArray("bus");
JSONObject jO = JA.getJSONObject(0);
System.out.println("#####################################");
System.out.println(jO.getString("BID"));
System.out.println("#####################################");
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println(error.networkResponse);
}
});
rq.add(r);
And I've searched for a solution, the only way is to edit the headers ! And I didn't find a way to edit headers via JAVA.

Related

Android Volley: Cannot pass data to server

I am trying to create a simple registration page for my android app. I am passing parameters with URL String and Storing those parameters in Database. Whenever i try to use string directly in browser the data is added to database without any error. However, When i try to pass data from Android Volley i am getting HTTP Error 409.
I have checked everything and still confused why this error is appearing only when i try to run url string from android app.
URL String:-
http://myurl.com/api/register.php?name=ahmed&email=obaid.ahmed#gmail.com&password=12345&membertype=Artist&joindate=24-Feb-2019
Java Code:-
JsonObjectRequest getRequest = new JsonObjectRequest(Request.Method.GET, urlFinal, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// display response
Log.d("Response", response.toString());
uploadImageToServer();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Error.Response", error.toString());
hideDialog();
}
}
);
First you need to understand about 409,
Explain here :- https://httpstatuses.com/409
And try to solve this on Server side where this Conflict issue occur.
And I recommend you to use URL Encoding before sending things in url,
Which is perform by :
Either by,
String query = URLEncoder.encode("apples oranges", "utf-8");
String url = "http://stackoverflow.com/search?q=" + query;
or By
String uri = Uri.parse("http://...")
.buildUpon()
.appendQueryParameter("key", "val")
.build().toString();
Which make your URL more compatible.
Or for More Better ways, There is an Library which i personally recommend to any android developer who love Light weight Volley for Api Integrations.
https://github.com/Lib-Jamun/Volley
dependencies {
compile 'tk.jamun:volley:0.0.4'
}
Cool Coding.

Authentication failed using volley

i am trying to get token from sever (Laravel) and saving to database(android) but when sending request to server i get this error:
E/Volley: [276] BasicNetwork.performRequest: Unexpected response code 401 for http://192.168.1.4:8000/api/user/login
E/Volley: [276] BasicNetwork.performRequest: Unexpected response code 401 for http://192.168.1.4:8000/api/user/login
D/error: com.android.volley.AuthFailureError
android code (java) :
public void loginUser(String email, String password, final OnLoginResponse onLoginResponse){
JSONObject requestJsonObject=new JSONObject();
try {
requestJsonObject.put("email",email);
requestJsonObject.put("password",password);
JsonObjectRequest request=new JsonObjectRequest(Request.Method.POST, "http://192.168.1.4:8000/api/user/login",requestJsonObject , new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
onLoginResponse.onResponse(response.optString("token"));
Log.d("response",response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("error",error.toString());
}
}) {
/**
* Passing some request headers*
*/
#Override
public Map getHeaders() throws AuthFailureError {
HashMap headers = new HashMap();
headers.put("Content-Type", "application/json");
headers.put("csrf-token", "X-XSRF-TOKEN");
return headers;
}
};
request.setRetryPolicy(new DefaultRetryPolicy(18000,DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
Volley.newRequestQueue(context).add(request);
} catch (JSONException e) {
Log.e(TAG, "loginUser: "+e.toString());
}
}
i checked client using postman , that is not problem and return token without problem.
this is screenshot of postman :
enter image description here
Probably the issue relies either in:
the headers
the variable name and password could be passed empty wrong or malformed once they reach the function login(...)
the parameters (maybe you are expecting more from the backend side)
could be an issue in backend (probably TokenMismatchException which relates to the csrf-token header I see in your Android Java code

android volley RequestQueue . code in php

I am setting up a sign in page for Android.
Android request code:
RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
StringRequest sr = new StringRequest(Request.Method.POST,"http://www.MY-URL.ir/signup.php", new Response.Listener<String>() {
#Override
public void onResponse(String response) {
System.out.println("--------------> res : " + response + " <------------------- res");
Toast.makeText(Main2Activity.this, "res", Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(Main2Activity.this, "-----------------> err", Toast.LENGTH_SHORT).show();
}
}){
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put("name","David Lee");
return params;
}
};
queue.add(sr);
PHP auntification code:
<?php
if(isset($_POST['name']))
{
$name=$_POST['name'];
$response = array();
$response['name'] = $name;
echo json_encode($response);
} else {
$no_data=array();
$no_data['none']= 'no data received';
echo json_encode($no_data);
}
?>
I am sending David Lee as a name and I want to insert it in a database (MySQL)
params.put("name","David Lee");
But I can't recognize the result of the request in my Php MySql table.
Is my code right?
Authentication request returns the following response:
System.out: --------------> res : <html><body><script type="text/javascript" src="/aes.js" ></script><script>function toNumbers(d){var e=[];d.replace(/(..)/g,function(d){e.push(parseInt(d,16))});return e}function toHex(){for(var d=[],d=1==arguments.length&&arguments[0].constructor==Array?arguments[0]:arguments,e="",f=0;f<d.length;f++)e+=(16>d[f]?"0":"")+d[f].toString(16);return e.toLowerCase()}var a=toNumbers("f655ba9d09a112d4968c63579db590b4"),b=toNumbers("98344c2eee86c3994890592585b49f80"),c=toNumbers("1ab6d8dc093d812e09e8e3d3ffcb99d5");document.cookie="__test="+toHex(slowAES.decrypt(c,2,a,b))+"; expires=Thu, 31-Dec-37 23:55:55 GMT; path=/"; location.href="http://www.papyrusmarket.ir/signup.php?i=1";</script><noscript>This site requires Javascript to work, please enable Javascript in your browser or use a browser with Javascript support</noscript></body></html> <------------------- res
How should back-end send the response to android? And how can I get it?

Android Volley - can't do a JSON request with POST, getting empty response

I am trying to make a json request using Volley library to a php server, but for some reason the server does not receive the json object I am sending, and it responds with empty string.
Here is my code
import android.content.Context;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response.Listener;
import com.android.volley.Response.ErrorListener;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;
public class MyVolley implements Listener, ErrorListener {
private static Context appContext;
public MyVolley(Context context) {
appContext = context;
}
public void stuff() throws JSONException {
RequestQueue queue = Volley.newRequestQueue(appContext);
JSONObject obj = new JSONObject();
obj.put("param1", "assda");
obj.put("param2", "fassfafsa");
JsonObjectRequest stringRequest = new JsonObjectRequest(Request.Method.POST, "some url here", obj, this, this);
queue.add(stringRequest);
}
#Override
public void onResponse(Object response) {
System.out.println(response);
}
#Override
public void onErrorResponse(VolleyError error) {
System.out.println(error);
}
}
And when it executes, this is what the server receives
array (
'Content-Type' => 'application/json; charset=utf-8',
'User-Agent' => 'pointless info here',
'Host' => 'some host here',
'Connection' => 'Keep-Alive',
'Accept-Encoding' => 'gzip',
'Content-Length' => '107',
) array (
) array (
)
Why could that be happening?
Make sure it's not a server side error (try your service using Postman for instance).
I personally faced the same issue some time ago, changing JsonObjectRequest to StringRequest fixed my problem.
Take a look at this link :
https://stackoverflow.com/a/31613565/7871886
Now I use Retrofit2 instead of Volley... Could be an option.
Happy coding
Not sure what was your problem, but for the future googlers:
My problem was that I was trying to read form $_POST instead of php://input
Full code (working):
Java:
JSONObject jsonobj; // declared locally so that it destroys after serving its purpose
jsonobj = new JSONObject();
try {
// adding some keys
jsonobj.put("new key", Math.random());
jsonobj.put("weburl", "hashincludetechnology.com");
// lets add some headers (nested JSON object)
JSONObject header = new JSONObject();
header.put("devicemodel", android.os.Build.MODEL); // Device model
header.put("deviceVersion", android.os.Build.VERSION.RELEASE); // Device OS version
header.put("language", Locale.getDefault().getISO3Language()); // Language
jsonobj.put("header", header);
// Display the contents of the JSON objects
display.setText(jsonobj.toString(2));
} catch (JSONException ex) {
display.setText("Error Occurred while building JSON");
ex.printStackTrace();
}
JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.POST, URL, jsonobj, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
System.out.println("onResponse()");
try {
result.setText("Response: " + response.toString(2))
System.out.println("Response: " + response.toString(2));
} catch (JSONException e) {
display.setText("Error Occurred while building JSON");
e.printStackTrace();
}
//to make sure it works backwards as well
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println("onErrorResponse()");
System.out.println(error.toString());
}
});
System.out.println("After the request is made");
// Add the request to the RequestQueue.
queue.add(jsObjRequest);
Clarification: display and result are two TextView objects I am using to display data on the screen, and queue is Volley's request queue.
PHP:
$inp = json_decode(file_get_contents('php://input')); //$input now contains the jsonobj
echo json_encode(["foo"=>"bar","input"=>$inp]); //to make sure we received the json and to test the response handling
Your Android Monitor should output sth. like :
{
"foo":"bar",
"input":{
"new key":0.8523024722406781,
"weburl":"hashincludetechnology.com",
"header": {
"devicemodel":"Android SDK built for x86",
"deviceVersion":"7.1",
"language":"eng"
}
}
}

Android Volley Cache on LastModified

The server returns a "Last Modified" header based on when the data changes. Need to use this to cache the response in volley.
My Volley request looks something like this:
StringRequest req = new StringRequest(Request.Method.GET, requestUrl, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray result = new JSONArray(response);
callback.onSuccess(result);
} catch (JSONException je) {
callback.onSuccess(new JSONArray());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("Error: " + error.getMessage());
}
});
Can find examples to cache based on a fixed time - say cache for 5 mins:
Android Setup Volley to use from Cache
But this doesnt solve my purpose. The server response has to be invalidated based on the "Last Modified" header. So I'm expecting volley to make the request and get a 304 Not Modified response and hence serve the content from the cache.
Even tried a custom header parser something like this:
https://github.com/mcxiaoke/android-volley/blob/master/src/main/java/com/android/volley/toolbox/HttpHeaderParser.java
But this doesnt seem to do the trick either.

Resources