Wierd results while trying to build an URI for HTTPGET - android

I'm trying to build an URL by adding some parameters to my BASEURL:
The problem is the parameters are added to my BASEURL in disorder, and characters as é are replaced by weird stuffs like %C3%A9
String BASEURI="myBaseUri";
void getParameters()
{
HashMap<String, String> map=new HashMap<String, String>();
final String login = ((EditText)alertDialogRegister.findViewById(R.id.regLogin)).getText().toString();
final String password= ((EditText)alertDialogRegister.findViewById(R.id.regPassword)).getText().toString();
final String passwordConfirm= ((EditText)alertDialogRegister.findViewById(R.id.regPasswordConfirm)).getText().toString();
final String firstName= ((EditText)alertDialogRegister.findViewById(R.id.regPrenom)).getText().toString();
final String lastName= ((EditText)alertDialogRegister.findViewById(R.id.regNom)).getText().toString();
final String sexe=((RadioButton)alertDialogRegister.findViewById(((RadioGroup)alertDialogRegister.findViewById(R.id.regSexe)).getCheckedRadioButtonId())).getText().toString();
final String email= ((EditText)alertDialogRegister.findViewById(R.id.regEmail)).getText().toString();
final String telephone= ((EditText)alertDialogRegister.findViewById(R.id.regPhone)).getText().toString();
final String adresse= ((EditText)alertDialogRegister.findViewById(R.id.regAddress)).getText().toString();
final String civilite=((RadioButton)alertDialogRegister.findViewById(((RadioGroup)alertDialogRegister.findViewById(R.id.regCivilite)).getCheckedRadioButtonId())).getText().toString();
map.put("rquest","addUser");
map.put("login", login);
map.put("password", password);
map.put("firstname", firstName);
map.put("lastname", lastName);
map.put("sex", sexe);
map.put("situation", civilite);
map.put("email", email);
map.put("address", adresse);
registeruser(map);
}
public void registeruser(HashMap<String,String> map)
{
Uri.Builder builder = Uri.parse(BASEURI).buildUpon();
builder.appendPath("api.php");
for(Map.Entry<String, String> entry:map.entrySet())
{
builder.appendQueryParameter(entry.getKey(),entry.getValue());
}
Uri builtUri = builder.build();
Log.i("Hossam", builtUri.toString());
HttpClient httpclient = new DefaultHttpClient();
HttpGet request = new HttpGet(builder.toString());
ResponseHandler<String> handler = new BasicResponseHandler();
String result = null;
try {
result = httpclient.execute(request, handler);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
httpclient.getConnectionManager().shutdown();
String tag = null;
//Log.i("http response", result);
}

The order issue, is because you are using a Map, and in Java Maps are unordered and unsorted type of collection, unless you use either LinkedHashMap or TreeMap which cost way more in performance than regular List, if you want specific order you must go for List, other way the Map will always return the values in an unordered way, and related to the special characters is because your URL contains them, and by default the URL is coneverted to its encoded version of them since they can only be ASCII, here is the list of the URL Encoded characters... http://www.degraeve.com/reference/urlencoding.php

Your characters é does not belong to ASCII character-set.
URLs can only contains ASCII character-set.
Since URLs often contain characters outside the ASCII set, the URL has to be converted into a valid ASCII format.
URL encoding replaces unsafe ASCII characters with a "%" followed by two hexadecimal digits.
URLs cannot contain spaces. URL encoding normally replaces a space with a + sign.
Source:w3schools

Related

How to parse unnamed JSON Array in Android app

I have a JSON array sent from my SQL server via PHP in the following format which I am finding difficult to parse without encountering errors.
[
{
"placename": "place1",
"latitude": "50",
"longitude": "-0.5",
"question": "place1 existed when?",
"answer1": "1800",
"answer2": "1900",
"answer3": "1950",
"answer4": "2000",
"correctanswer": "1900"
},
{
"placename": "place2",
"latitude": "51",
"longitude": "-0.5",
"question": "place2 existed when?",
"answer1": "800",
"answer2": "1000",
"answer3": "1200",
"answer4": "1400",
"correctanswer": "800"
},
{
"placename": "place3",
"latitude": "52",
"longitude": "-1",
"question": "place 3 was established when?",
"answer1": "2001",
"answer2": "2005",
"answer3": "2007",
"answer4": "2009",
"correctanswer": "2009"
}
]
I have verified my JSON at JSONLint and it comes up as valid. I have also used log code to print out my JSON in the Eclipse app debugger after my HTTP client has processed it and that also works fine (it shows the JSON as above so I know it has downloaded correctly).
I'm trying to fit the JSON Parser into the following activity but all my attempts thus far have either contained too many errors to run or have simply returned no results because of JSON parsing errors.
Here is the code of the main activity. The code for this activity is adapted from NewThinkTank.com (Android Development 15) and I'm trying to tweak it for my needs but the structure of the JSON used in the example is very different to mine.
I was hoping someone could suggest some code, or give me some pointers, as to how I could go about parsing this JSON array properly. I am fairly new to Android programming so this is a fairly steep task to figure out on my own.
Thanks for your time.
public class MainActivity extends Activity {
// The JSON REST Service I will pull from
static String dlquiz = "http://exampleserver.php";
// Will hold the values I pull from the JSON
static String placename = "";
static String latitude = "";
static String longitude = "";
static String question = "";
static String answer1 = "";
static String answer2 = "";
static String answer3 = "";
static String answer4 = "";
static String correctanswer = "";
#Override
public void onCreate(Bundle savedInstanceState) {
// Get any saved data
super.onCreate(savedInstanceState);
// Point to the name for the layout xml file used
setContentView(R.layout.main);
// Call for doInBackground() in MyAsyncTask to be executed
new MyAsyncTask().execute();
}
// Use AsyncTask if you need to perform background tasks, but also need
// to change components on the GUI. Put the background operations in
// doInBackground. Put the GUI manipulation code in onPostExecute
private class MyAsyncTask extends AsyncTask<String, String, String> {
protected String doInBackground(String... arg0) {
// HTTP Client that supports streaming uploads and downloads
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
// Define that I want to use the POST method to grab data from
// the provided URL
HttpPost httppost = new HttpPost(dlquiz);
// Web service used is defined
httppost.setHeader("Content-type", "application/json");
// Used to read data from the URL
InputStream inputStream = null;
// Will hold the whole all the data gathered from the URL
String result = null;
try {
// Get a response if any from the web service
HttpResponse response = httpclient.execute(httppost);
// The content from the requested URL along with headers, etc.
HttpEntity entity = response.getEntity();
// Get the main content from the URL
inputStream = entity.getContent();
// JSON is UTF-8 by default
// BufferedReader reads data from the InputStream until the Buffer is full
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
// Will store the data
StringBuilder theStringBuilder = new StringBuilder();
String line = null;
// Read in the data from the Buffer untilnothing is left
while ((line = reader.readLine()) != null)
{
// Add data from the buffer to the StringBuilder
theStringBuilder.append(line + "\n");
}
// Store the complete data in result
result = theStringBuilder.toString();
} catch (Exception e) {
e.printStackTrace();
}
finally {
// Close the InputStream when you're done with it
try{if(inputStream != null)inputStream.close();}
catch(Exception e){}
}
//this allowed me to verify the JSON download in the debugger
Log.v("JSONParser RESULT ", result);
// JSON parsing needs to happen here...
return result;
}
protected void onPostExecute(String result){
// Gain access so I can change the TextViews
TextView line1 = (TextView)findViewById(R.id.line1);
TextView line2 = (TextView)findViewById(R.id.line2);
TextView line3 = (TextView)findViewById(R.id.line3);
// Change the values for all the TextViews
line1.setText("Place Name: " + placename);
line2.setText("Question: " + question);
line3.setText("Correct Answer: " + correctanswer);
}
}
}
Check this answer out: How to parse JSON in Android
You'll be using:
JSONArray array = new JSONArray(result);
From there, you'll loop through and get each JSONObject:
for(int i = 0; i < array.length(); i++)
{
JSONObject obj = array.getJSONObject(i);
//now, get whatever value you need from the object:
placename = obj.getString("placename");
//or if on the MainUI thread you can set your TextView from here:
yourTextView.setText(obj.getString("placename"));
}
Good luck!

Iterating through JSON data converted from multidimensional array

THIS WORKS FINE
I have this code block to read a json data that I am getting from FetchData.php file; My code looks like this:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.2.2/mydummyproject/FetchData.php");
TextView textView = (TextView)findViewById(R.id.textView1);
try {
HttpResponse response = httpclient.execute(httppost);
String jsonResult = inputStreamToString(response.getEntity().getContent()).toString();
JSONObject object = new JSONObject(jsonResult);
String name = object.getString("name");
String verion = object.getString("version");
textView.setText(name + " - " + verion);
}
catch (JSONException e) {
e.printStackTrace();
}
Data from my PHP File FetchData.php
{"name":"John Doe","version":"Android 4.4"}
PROBLEM
I also have another type of data coming from FetchDataTwo.php
[{"name":"John Doe","version":"Android 4.4"}, {"name":"Seliana Gomez","version":"Android 4.1"}, {"name":"Nerdy Trumph","version":"Android 4.4"}]
Now the above one is also a json data that I have got by doing json_encode($multidimensional_array) in PHP file.
ISSUE
How to loop over this multidimensional encoded array from json. So that I can iterate over like this (json data by json data):
[NOTE: Below is the data that I need to fetch, I don't want to arrange in the displayed fashion. That's just for clarity and example]
Name | Version
John Doe | Android 4.4
Seliana Gomez | Android 4.1
Nerdy Trumph | Android 4.4
Basically as a logic something like this:
//Loop over each json object
for data in JSONObject:
// Print name and version
textView.setText(data.name + " - " + data.version)
It looks like all you have to do is iterate over the JSONArray
try {
JSONArray array = new JSONArray(inputString);
for (int i = 0; i < array.length(); i++) {
JSONObject jsonObject = array.optJSONObject(i);
// Json Object handling...
}
} catch (JSONException e) {
// handle
}
But really, using Gson should be way easier. It can parse the contents for you into a simple java object. You can annotate a POJO class with the field names and Gson does all the work.
public class NameVersionPair {
private interface Json {
String NAME = "name";
String VERSION = "version";
}
#SerializedName(Json.NAME)
private String mName;
#SerializedName(Json.VERSION)
private String mVersion;
public String getName() {
return mName;
}
public String getVersion() {
return mVersion;
}
}
Then use a Gson instance to parse your string automatically
Gson gson = new Gson();
NameVersionPair[] result = gson.fromJson(inputString, NameVersionPair[].class);

Android UTF-8 encoding for text

I have an android application which get jSON data through HttpGet. But I am facing some problem when I show the data in the text view. The second name in the JSON data shows like my attached photo below. But when I show the jSON data in browser it shows wrong like my photo. Sorry for my poor English.
Here is my activity:
HttpClient client = new DefaultHttpClient();
String url = "http://54.228.199.162/api/campaigns";
try {
String res;
HttpGet httpget = new HttpGet(url);
ResponseHandler<String> reshan = new BasicResponseHandler();
res = client.execute(httpget, reshan);
Log.d("um1", res);
JSONArray jsonArray = new JSONArray(res);
//campaign.setText(res);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String id = jsonObject.getString(TAG_ID);
byte[] b = id.getBytes("utf-8");
String utfid = new String(b);
String name = jsonObject.getString(TAG_NAME);
byte[] s = name.getBytes("utf-8");
String utfname = new String(s);
Log.d("IDDDDDDD", id);
Log.d("Nameeeeeee", name);
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, utfid);
map.put(TAG_NAME, utfname);
//Object contactList;
contactList.add(map);
}
HttpResponse httpresponse = client.execute(httpget);
int responsecode = httpresponse.getStatusLine().getStatusCode();
Log.d("responsenummmm", "um11111"+responsecode);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
};
Here is the jSON data file:
[{"_id":"520ba75acf17c8cc796b584b","name":"Oulu Liikkujan viikko 16-22.9.2013"},
{"_id":"52161d80ecaf181dc5982624","name":"Ylöjärvi Liikkujan viikko 16-22.9.2013"},
{"_id":"52262fa6d3ee051600d84c68","name":"Lapin yliopiston hyvinvointiviikko 16-22.9.2013"},
{"_id":"5293bbffbf2f15044800011d","name":"testi"}, {"_id":"52a318bbac059a0002000b4f","name":"Standing wave to Oulu"}]
Here is the problem in Text view:
The name of the second one in the text view(photo) should be look like:Ylöjärvi Liikkujan viikko 16-22.9.2013
Please help me.
write like this Html.fromHtml(YOUR STRING)
Try to decode your your value as below :
String decodedString = URLDecoder.decode(jsonObject.getString(TAG_ID), "UTF-8");
use this to display the name..
Html.fromHtml("<font color='#ffff0000'>enter...label</font>")

org.json.JSONException: Value <!DOCTYPE of type java.lang.String cannot be converted to JSONObject

Here I want to display the JSON content using API key. But I am unable to get the authentication.
I am getting the error in JsonObject:
org.json.JSONException: Value Authorization of type java.lang.String cannot be converted to JSONObject
In my android application, I just pass the API key and URL id to get the JSON response in the following URL. I display the JSON content using JSON array.
But if I:
public class AndroidAPiActivity extends Activity {
/*
* FlickrQuery = FlickrQuery_url
* + FlickrQuery_per_page
* + FlickrQuery_nojsoncallback
* + FlickrQuery_format
* + FlickrQuery_tag + q
* + FlickrQuery_key + FlickrApiKey
*/
String FlickrQuery_url = "http://192.138.11.9/api/interests/";
String FlickrQuery_per_page = "&per_page=1";
String FlickrQuery_nojsoncallback = "&nojsoncallback=1";
String FlickrQuery_format = "&format=json";
String FlickrQuery_tag = "&tags=";
String FlickrQuery_key = "&api_key=";
// Apply your Flickr API:
// www.flickr.com/services/apps/create/apply/?
String FlickrApiKey = "f65215602df8f8af";
EditText searchText;
Button searchButton;
TextView textQueryResult, textJsonResult;
ImageView imageFlickrPhoto;
Bitmap bmFlickr;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
searchText = (EditText)findViewById(R.id.searchtext);
searchButton = (Button)findViewById(R.id.searchbutton);
textQueryResult = (TextView)findViewById(R.id.queryresult);
textJsonResult = (TextView)findViewById(R.id.jsonresult);
imageFlickrPhoto = (ImageView)findViewById(R.id.flickrPhoto);
searchButton.setOnClickListener(searchButtonOnClickListener);
}
private Button.OnClickListener searchButtonOnClickListener
= new Button.OnClickListener(){
public void onClick(View arg0) {
// TODO Auto-generated method stub
String searchQ = searchText.getText().toString();
String searchResult = QueryFlickr(searchQ);
textQueryResult.setText(searchResult);
String jsonResult = ParseJSON(searchResult);
textJsonResult.setText(jsonResult);
if (bmFlickr != null){
imageFlickrPhoto.setImageBitmap(bmFlickr);
}
}};
private String QueryFlickr(String q){
String qResult = null;
String qString =
FlickrQuery_url
+ FlickrQuery_per_page
+ FlickrQuery_nojsoncallback
+ FlickrQuery_format
+ FlickrQuery_tag + q
+ FlickrQuery_key + FlickrApiKey;
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(qString);
try {
HttpEntity httpEntity = httpClient.execute(httpGet).getEntity();
if (httpEntity != null){
InputStream inputStream = httpEntity.getContent();
Reader in = new InputStreamReader(inputStream);
BufferedReader bufferedreader = new BufferedReader(in);
StringBuilder stringBuilder = new StringBuilder();
String stringReadLine = null;
while ((stringReadLine = bufferedreader.readLine()) != null) {
stringBuilder.append(stringReadLine + "\n");
}
qResult = stringBuilder.toString();
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return qResult;
}
private String ParseJSON(String json){
String jResult = null;
bmFlickr = null;
String key_id;
String category;
String subcategory;
String title;
String icon_image;
try
{
JSONObject JsonObject = new JSONObject(json);
JSONObject Json_photos = JsonObject.getJSONObject("interests");
JSONArray JsonArray_photo = Json_photos.getJSONArray("interest");
//We have only one photo in this exercise
JSONObject FlickrPhoto = JsonArray_photo.getJSONObject(0);
key_id = FlickrPhoto.getString("row_key");
category = FlickrPhoto.getString("category");
subcategory = FlickrPhoto.getString("subcategory");
title = FlickrPhoto.getString("title");
jResult = "\n key_id: " + key_id + "\n"
+ "category: " + category + "\n"
+ "subcategory: " + subcategory + "\n"
+ "title: " + title + "\n";
bmFlickr = LoadPhotoFromFlickr(key_id, category, subcategory,title);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return jResult;
}
private Bitmap LoadPhotoFromFlickr(
String key_id, String category, String subcategory,
String title){
Bitmap bm= null;
String icon_image = null;
// String FlickrPhotoPath ="";
String FlickrPhotoPath ="http://182.72.180.34/media/"+icon_image+".jpg";
URL FlickrPhotoUrl = null;
try {
FlickrPhotoUrl = new URL(FlickrPhotoPath);
HttpURLConnection httpConnection = (HttpURLConnection) FlickrPhotoUrl.openConnection();
httpConnection.setDoInput(true);
httpConnection.connect();
InputStream inputStream = httpConnection.getInputStream();
bm = BitmapFactory.decodeStream(inputStream);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return bm;
}
}
Update:
Based on the HTML response, I can tell you that this is not JSON. The response tells me that you have the incorrect URL for your web service.
You need to check your URL.
Extra Info / Previous Answer:
It looks like the simple answer is the right one - your result is not a valid JSON string. See JSON.org website for details on what JSON should look like.
Check out JSON Parser Online - I find its very useful when working with JSON.
It is strange that you are requesting JSON, and it is not returning it properly - perhaps I have missed something.
Yes, we get such kind of warning when the given URL is not valid.
Just check the URL once.
Remove docType from API. and set content Type Application/json .
(as text/html will not read as json . thus you were seeing the error.)
May be this can help
https://teamtreehouse.com/community/solved-exception-cannot-convert-string-type-to-json-object
Solved.
It turns out the runtime error stretched back to the previous video.
I was doing
JSONObject currently = new JSONObject("currently");
instead of
JSONObject currently = forecast.getJSONObject("currently");
So my guess is Android thought I was trying to setup an entirely new JSON object instead of trying to retrieve information from an existing one! :) Now the console displays the time perfectly!
I've faced this issue too, I changed my Internet connection to another network and it works.
The problem was that ISP doesn't accept http access.
Another solution you can open VPN and try again, and maybe it works...
HOW I FIXED THE FOLLOWING ERRORS:
=============================================================================
org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject
org.json.JSONException: Value permissions of type java.lang.String cannot be converted to JSONObject
==============================================================================
This might not apply to this particular scenario, but it comes up as a top search result for the given issue/keyword.
So, i bought a script from a professional vendor on codecanyon.
The script consisted of 3x main parts;
- MAIN CART SITE (PHP)
- MAIN ADMIN SITE + /API (PHP)
- ANDROID ADMIN APP (JAVA)
I found many issues once the script was installed. Ranging from incomplete or missing table arrays on the MAIN CART SITE, then i had a problem on the ANDROID ADMIN APP that (upon inspection of logs) revealed a mysqli_exception was to blame.
So after hours of messing around with loops and trying to figure out where the issue was. After actually learning how to dump output to the logs / logcat. I was able to determine that it was in actual fact, a;
BREAKING CHANGE SINCE MYSQL-8
TO FIX, RUN THE FOLLOWING COMMANDS IN mysql TERMINAL;
SET GLOBAL sql_mode = '';
SET SESSION sql_mode = '';
THIS REMOVES THE 'STRICT MODE' amongst other rules that has caused me so much grief over the last few days. Thought i'd better share the answer, hopefully save someone else days of eye-drying torment =].
Remember to reintroduce the default ruleset one rule at a time and test to see what modes your app can support (if this solution fixes your problem) as they are no doubt essential security/data-integrity measures that are there for good reason. Ideally, update codebase to comply with current standards. Unfortunately that's way beyond me at this stage.
Hope this works for you guys.
I received the same "<!Doctype..." error when working with Google Translate's json URLs. Then, I found this code somewhere and it worked :
BasicHttpParams basicHttpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout((HttpParams)basicHttpParams, (int)10000);
HttpConnectionParams.setSoTimeout((HttpParams)basicHttpParams, (int)10000);
HttpConnectionParams.setTcpNoDelay((HttpParams)basicHttpParams, (boolean)true);
DefaultHttpClient defaultHttpClient = new DefaultHttpClient((HttpParams)basicHttpParams);
HttpGet httpGet = new HttpGet(url);
BasicResponseHandler basicResponseHandler = new BasicResponseHandler();
JSONObject json=null;
try {
json = new JSONObject((String)defaultHttpClient.execute((HttpUriRequest)httpGet, (ResponseHandler)basicResponseHandler));
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

URL encoding in Android

How do you encode a URL in Android?
I thought it was like this:
final String encodedURL = URLEncoder.encode(urlAsString, "UTF-8");
URL url = new URL(encodedURL);
If I do the above, the http:// in urlAsString is replaced by http%3A%2F%2F in encodedURL and then I get a java.net.MalformedURLException when I use the URL.
You don't encode the entire URL, only parts of it that come from "unreliable sources".
Java:
String query = URLEncoder.encode("apples oranges", Charsets.UTF_8.name());
String url = "http://stackoverflow.com/search?q=" + query;
Kotlin:
val query: String = URLEncoder.encode("apples oranges", Charsets.UTF_8.name())
val url = "http://stackoverflow.com/search?q=$query"
Alternatively, you can use Strings.urlEncode(String str) of DroidParts that doesn't throw checked exceptions.
Or use something like
String uri = Uri.parse("http://...")
.buildUpon()
.appendQueryParameter("key", "val")
.build().toString();
I'm going to add one suggestion here. You can do this which avoids having to get any external libraries.
Give this a try:
String urlStr = "http://abc.dev.domain.com/0007AC/ads/800x480 15sec h.264.mp4";
URL url = new URL(urlStr);
URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(), url.getQuery(), url.getRef());
url = uri.toURL();
You can see that in this particular URL, I need to have those spaces encoded so that I can use it for a request.
This takes advantage of a couple features available to you in Android classes. First, the URL class can break a url into its proper components so there is no need for you to do any string search/replace work. Secondly, this approach takes advantage of the URI class feature of properly escaping components when you construct a URI via components rather than from a single string.
The beauty of this approach is that you can take any valid url string and have it work without needing any special knowledge of it yourself.
For android, I would use
String android.net.Uri.encode(String s)
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.
Ex/
String urlEncoded = "http://stackoverflow.com/search?q=" + Uri.encode(query);
Also you can use this
private static final String ALLOWED_URI_CHARS = "##&=*+-_.,:!?()/~'%";
String urlEncoded = Uri.encode(path, ALLOWED_URI_CHARS);
it's the most simple method
try {
query = URLEncoder.encode(query, "utf-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
you can use below methods
public static String parseUrl(String surl) throws Exception
{
URL u = new URL(surl);
return new URI(u.getProtocol(), u.getAuthority(), u.getPath(), u.getQuery(), u.getRef()).toString();
}
or
public String parseURL(String url, Map<String, String> params)
{
Builder builder = Uri.parse(url).buildUpon();
for (String key : params.keySet())
{
builder.appendQueryParameter(key, params.get(key));
}
return builder.build().toString();
}
the second one is better than first.
Find Arabic chars and replace them with its UTF-8 encoding.
some thing like this:
for (int i = 0; i < urlAsString.length(); i++) {
if (urlAsString.charAt(i) > 255) {
urlAsString = urlAsString.substring(0, i) + URLEncoder.encode(urlAsString.charAt(i)+"", "UTF-8") + urlAsString.substring(i+1);
}
}
encodedURL = urlAsString;

Categories

Resources