Android Volley: Cannot pass data to server - java

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.

Related

android volley - can't read data from local host

I wrote android app to read json using volley.
If i use example URL from internet - i don't have problem, the data is read. But when i try to read data from local host, I am getting an error.
The same data i can see in web browser in my emulator.
my URL: "http://10.0.2.2/volley_sample/get_data.php"
my code:
private void sendGetRequest() {
RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
String url = "http://10.0.2.2/volley_sample/get_data.php"; //it doesn't work
//String url ="https://reqres.in/api/users/2"; //it works
// 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 10 characters of the response string.
get_response_text.setText("Response is: " + response.substring(0, 10));
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
get_response_text.setText("That didn't work!");
}
});
// Add the request to the RequestQueue.
queue.add(stringRequest);
}
adres "http://10.0.2.2/volley_sample/get_data.php" works in web browser in my emulator.
I tried also "http://192.168....", "127.0.0.1....", "localhost/volley_sample...." etc., and neither works.
adres "https://reqres.in/api/users/2" (example from internet) work without problem.
ofc. i added "<uses-permission android:name="android.permission.INTERNET"/>"
I have no idea what I am doing wrong :(

Internal server error while connecting to Server in android using volley?

here my function code to post using volley
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_CHECK_IN,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
int status = jsonObject.getInt("status");
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError response) {
}
}) {
#Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
#Override
public byte[] getBody() throws AuthFailureError {
try {
return requestBody == null ? null : requestBody.getBytes("utf-8");
} catch (UnsupportedEncodingException uee) {
VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", requestBody, "utf-8");
return null;
}
}
#Override
public Map<String, String> getHeaders () {
Map<String, String> map = new HashMap<String, String>();
map.put("Content-Type", "application/json");
map.put("appid", appids);
map.put("timestamp", timestamps);
map.put("token", tokens);
map.put("signature", signatures);
return map;
}
};
}
I don't know what's wrong with my code, because of 2 days ago everything fine.
and when I tried to debug, error show like this
BasicNetwork.performRequest: Unexpected response code 500 for http://api/presence/check_in
can anyone help me, please? because I'm stuck and need help or reference to solve my error
thank you
HTTP code 500 is Internal Server Error. Read more here. It generally implies that server is not able to process the request and come up with a response. This means that the code for your application might be alright whereas the server might be encountering some issue processing the current request body. I see that you are sending String in your request body. One peculiar thing I noticed with sending String in request body is that, we also need to check if the String is null or not, better to to use .trim() method at the end of your string too, which will delete starting and trailing spaces. Something simple like not escaping single quotes ( ' ) for the field you are trying to insert onto the database at your server might cause this. So server side field validation and best practices like Prepared Statements is also crucial. If you are absolutely sure that your client end [android app] is alright, maybe the server is encountering some issue at the endpoint you are hitting.
Test your api with a rest client like POSTMAN or INSOMNIA to be absolutely sure that your server and api layer is working as intended. Good Luck

How to form an URL in Background thread before using it with an API?

I am working with an API for the first time.
My need is that I need to form an URL with certain parameters out of which one parameter cannot be formed in the Main UI thread and has to be formed in the Background thread.
I am planning to use to volley library to post the GET request.
I am using the Needle library which helps in running background tasks. This is What I have tried till now.
Needle.onBackgroundThread().execute(new UiRelatedTask<String>() {
#Override
protected String doWork() {
return url = GetUrl();
}
#Override
protected void thenDoUiRelatedWork(String result1) {
Log.e("JSON", url);
final JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener() {
#Override
public void onResponse(Object response) {
Log.e("JSON", response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("JSON", error.toString());
}
});
RequestQueue queue = VolleyController.getInstance(Activity.this.getApplicationContext()).getRequestQueue();
queue.start();
queue.add(jsonObjectRequest);
}
});
But the Main problem is that After the GetUrl() method immediately the thenDoUiRelatedWork method is called hence the request is made using an Invalid URL as the URL will still be loading in the background and then when the loading of the URL is over I am logging the URL Which is right.
I cannot use an AysncTask as my app is already using three AsyncTaks and additionally two more could be activated by the user based on the feature he is using. And also the API request has to be done in various places (3-4 places) hence using an AsyncTask will not be suitable.
Can anyone help me to first form the URL fully in the Background and the use volley to post the GET request.

How can I use the WooCommerce REST API in an Android app? [duplicate]

This question already has an answer here:
How do I call REST API from an android app? [closed]
(1 answer)
Closed 4 years ago.
I have generated the key and secret now I don't know how to use the key and secret so that I can get the data from server into my Android app. Can anyone tell the the proper procedure of it? How can i Create the signature , nonce and other things t authenticate ?
Using Volley library is the easiest way to connect to APIs. For example
RequestQueue queue = Volley.newRequestQueue(this);
String url = this.apiURl; //you could store it as config at raw
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// do nice things with your beautiful response
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// Handle error if any
}
});
queue.add(jsonObjectRequest);
Woocommerce sends json response so use the JsonObjectRequestso you need not convert the String to Json again.
Hope this helps!

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.

Categories

Resources