encode url to fetch JSON data - android

I am trying to fetch json data from remote server. Everything works fine just when a two character string is passed my app gets force stopped. How to encode the url to prevent this error
here is how am trying to fetch json values
jsonobject = JSONfunctions.getJSONfromURL("http://www.example.com/index.php?sutyp="+sutyp);
If i pass "Hello" through sutyp there is no error but if i pass "Hello World" app force stops
How do I encode the url to prevent this. Any suggestions would be of great help

You need to use the android.net.Uri class:
String url = Uri.parse("http://www.example.com/index.php")
.buildUpon()
.appendQueryParameter("sutyp", sutyp)
.build()
.toString();
jsonobject = JSONfunctions.getJSONfromURL(url);
From the docs:
Encodes characters in the given string as '%'-escaped octets using the
UTF-8 scheme. Leaves letters ("A-Z", "a-z"), numbers ("0-9"), and
unreserved characters ("_-!.~'()*") intact. Encodes all other
characters.

You could use URLEncoder.encode(string, "utf-8")
For example
String url = String.format("http://www.example.com/index.php?sutyp=%s", sutyp);
jsonobject = JSONfunctions.getJSONfromURL(URLEncoder.encode(url, "utf-8");
Here is a reference to the documentation

Related

How to convert Json string into Json Array in Android Studio Java

I have a Json String like below
["Monday","Tueday","wednesday","Thuesday","Friday","Saturday"]
What I want to do is send this Json String to a web server using the android studio volley library.
SO I keep getting this error
com.android.volley.ParseError: org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONArray
The string cannot be converted to JsonArray.
So I have 2 questions I need help with.
My first is how to convert string to JsonArray. For example below String.
["Monday","Tueday","wednesday","Thuesday","Friday","Saturday"]
My second question is about passing this Jason Array (once we create) to a web server. I was researching about the Hashmap but I don't know how to send the JsonArray in Hashmap.
I had a go with below code, but it did not work.
#Override
protected Map<String, String> getParams() throws AuthFailureError {
return super.getParams();
}
I don't know how to send JsaonArray in hashmap.
So Overall, I would like to send this above string to web server.
Supose that the name of string is myString.
rString = myString.replace('[','');
rString = rString.replace(']','');
rString = rString.replace('"','');
String split[] = rString.split(',').
Now you have an array called split with every position is a day.
Edit: This is for frist question
Use that
JSONArray yourJsonArray = JSONArray.fromObject(yourJson);
Answer to first question:
I think it's not the exact response from the server, and there's a HTML <br> tag in the response.
because the line Value <br of type java.lang.String cannot be... clearly contains string <br, try replacing the HTML tags and/or decoding/unescaping the HTML tags to plain text, AND then you can convert that plain JSON text to JSONArray.
this snippet might help you out with decoding the response:
String parsedReponse = Html.fromHtml(serverResponse).toString()
if (parsedReponse != null) parsedReponse = parsedReponse.trim();
Answer to second question:
check out OkHttp3 and Retrofit libraries, they're pretty popular and amazing.
those can help you send POST data to your server
hope that helped you :)

how to pass value at runtime in url in android using json parsing?

i am trying to get name and address of hospitals,atm's,restaurants ....etc. near by my location with the help of google near by places api so i use json parsing ,since i can able to get all the name and address but only problem is that i can't understand that how can i get different values of ex. hotel,hospital,atm,bank...etc. using same url by putting different different values in run time.here is my url ....
https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=26.841,75.801&radius=5000&types=hospital&key=AIzaSyBstND0mA7NZJPulZRcNtoWyJwXaKxqsFI";
In the above url there is a field "types" ,here i want to pass different different values at run time.....like hotel,hospital,bank,atm ...etc.
String type = "hospital";
int radius =5000;
String string = String.format("https://maps.googleapis.com/maps/api/place/nearbysearch
/json?location=26.841,75.801&radius=%d&types=%s&
key=AIzaSyBstND0mA7NZJPulZRcNtoWyJwXaKxqsFI", radius, type);
You can use Uri to build this
String base="https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=26.841,75.801";
String RADIUS="5000";
String TYPES="hospital";
String KEYS="AIzaSyBstND0mA7NZJPulZRcNtoWyJwXaKxqsFI";
Uri builtUri=Uri.parse(base).buildUpon()
.appendQueryParameter("radius",RADIUS)
.appendQueryParameter("types",TYPES)
.appendQueryParameter("key",KEYS)
.build();
URL url=new URL(builtUri.toString());
OUTPUT
https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=26.841,75.801&radius=5000&types=hospital&key=AIzaSyBstND0mA7NZJPulZRcNtoWyJwXaKxqsFI
You can easily change value of RADIUS,TYPES on runtime

Sending Json Array with Http Get in Android

iam calling a webservice(php http get request)
http://website.com/admin/employee_login.php?fun_name=abc&company_code=1&employee_ss=123&gtime=02:22 PM&x_id=350&v_id=9&task={"Walking":"1","Transfers":"1","OstomyCare":"1"}
but when am encoding this url am getting something different with %20 something like that, and it's not updating the tasks in the server database. Is there any method where i can pass parameters as a json array without encoding like same above ?
thank you
Before sending the url and parameters are url encoded. For instance spaces become %20. On the receiving side php should url decode the parameters. There is a php function which does that for you. After that you have the original parameters back.
use:
String value = "my url value"; // put here your url
URLEncoder.encode(value,"UTF-8")

Parse \u00 string android

I want to parse a string which is encoded in \u00 characters (like \u003e, \u003c etc) into normal string so that I can load it in webview. May I know how to parse it? I searched a lot on internet, but all results were php related.
EDIT: The string is here: http://pastie.org/8950227
I want to display it in webview, but it is displaying plain text.
Your data looks like it is a valid JSON string literal. You can use JSONTokener to parse it:
String data = ...;
String parsed = (String)new JSONTokener(data).nextValue();

Encoding Special characters in Android Json object

I am sending json object to server, My url having json object.Json object having special characters,how to encoding special characters in android, please help me.Thanks in advance.
Use UrlEncode.encode(yourstring, "UTF-8");
If I understood you, you want to send a json object using the url itself (that is, as a parameter). If security doesn't matter you (it will be visible), you could just encode using [Base64][1].
You should probably play with your json object to convert it to a byte[], called jsonbytes, for instance, then use Base64.encodeToString(jsonbytes, Base64.URL_SAFE) and sending this as a parameter.
Your server then should convert this Base64 encoded string into a json object, which tends to be straightforward if you're using PHP:
$jsonString = base64_decode($_GET['json']);
$json = json_decode($jsonString, TRUE);
This will give you an associative array in PHP. If you just want the json string, skip the last step.

Categories

Resources