I want encoded URL having India language in query string. e.g.
http://online3.esakal.com/NewsDetails.aspx?NewsId=4741992566950155024&SectionId=10SectionName=पुणे&NewsTitle=पुण्यात गणरायाला उत्साहात निरोप (फोटोफीचर1)
if I load above URL in the web-view of android, i get following URL in onPageFinished callback method of WebViewClient.
encoded url from webview client :
http://online3.esakal.com/NewsDetails.aspx?NewsId=4741992566950155024&SectionId=10SectionName=%E0%A4%AA%E0%A5%81%E0%A4%A3%E0%A5%87&NewsTitle=%E0%A4%AA%E0%A5%81%E0%A4%A3%E0%A5%8D%E0%A4%AF%E0%A4%BE%E0%A4%A4%20%E0%A4%97%E0%A4%A3%E0%A4%B0%E0%A4%BE%E0%A4%AF%E0%A4%BE%E0%A4%B2%E0%A4%BE%20%E0%A4%89%E0%A4%A4%E0%A5%8D%E0%A4%B8%E0%A4%BE%E0%A4%B9%E0%A4%BE%E0%A4%A4%20%E0%A4%A8%E0%A4%BF%E0%A4%B0%E0%A5%8B%E0%A4%AA%20(%E0%A4%AB%E0%A5%8B%E0%A4%9F%E0%A5%8B%E0%A4%AB%E0%A5%80%E0%A4%9A%E0%A4%B01)
But if i used following code to encode original url, i get follwoing url after encoding:
try {
String url1 = "http://online3.esakal.com/NewsDetails.aspx?" +
"NewsId=4741992566950155024&SectionId=10SectionName=पुणे&NewsTitle=पुण्यात गणरायाला उत्साहात निरोप (फोटोफीचर1)";
URL url = new URL(url1);
URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(),
url.getPort(), url.getPath(), URLEncoder.encode(url.getQuery(), "UTF-8"), url.getRef());
url = uri.toURL();
String str1 = url.toString();
}catch(Exception e) {
System.out.println(""+e);
}
: http://online3.esakal.com/NewsDetails.aspx?NewsId%253D4741992566950155024%2526SectionId%253D10SectionName%253D%25E0%25A4%25AA%25E0%25A5%2581%25E0%25A4%25A3%25E0%25A5%2587%2526NewsTitle%253D%25E0%25A4%25AA%25E0%25A5%2581%25E0%25A4%25A3%25E0%25A5%258D%25E0%25A4%25AF%25E0%25A4%25BE%25E0%25A4%25A4+%25E0%25A4%2597%25E0%25A4%25A3%25E0%25A4%25B0%25E0%25A4%25BE%25E0%25A4%25AF%25E0%25A4%25BE%25E0%25A4%25B2%25E0%25A4%25BE+%25E0%25A4%2589%25E0%25A4%25A4%25E0%25A5%258D%25E0%25A4%25B8%25E0%25A4%25BE%25E0%25A4%25B9%25E0%25A4%25BE%25E0%25A4%25A4+%25E0%25A4%25A8%25E0%25A4%25BF%25E0%25A4%25B0%25E0%25A5%258B%25E0%25A4%25AA+%2528%25E0%25A4%25AB%25E0%25A5%258B%25E0%25A4%259F%25E0%25A5%258B%25E0%25A4%25AB%25E0%25A5%2580%25E0%25A4%259A%25E0%25A4%25B01%25291
I do not understand that how does web-view does the url encoding?
Related
I try to download an image via bing image search api. I get an error after open the connection to the endpoint:
java.io.FileNotFoundException: https://api.cognitive.microsoft.com/bing/v7.0/images/search?q=Der+Rueckkehrer+Bluray
Here my code:
String subscriptionKey = "my sub key";
String host = "https://api.cognitive.microsoft.com";
String path = "/bing/v7.0/images/search";
URL url = new URL(host + path + "?q=" + URLEncoder.encode(productName, "UTF-8"));
HttpsURLConnection connection = (HttpsURLConnection)url.openConnection();
connection.setRequestProperty("Ocp-Apim-Subscription-Key", subscriptionKey);
System.out.println("URL " + url);
// receive JSON body
InputStream stream = connection.getInputStream(); <--- Crash
bingResult = readStream(stream);
I am developing an Android app in which I am retrieving an image from a server and show it in an image view using Picasso. Some image URLs don't work even though I can test them successfully in a browser.
For example this URL works correctly:
http://www.tonightfootballreport.com/\Filebucket\Picture\image\png\20160730011032_BPL.png
But this one fails:
http://www.tonightfootballreport.com/\Filebucket\Picture\image\png\20160807025619_Serie A.png
The difference appears to be that the failing URL contains a space. What do I need to do to make this work?
String temp = "http://www.tonightfootballreport.com/\Filebucket\Picture\image\png\20160807025619_Serie A.png";
temp = temp.replaceAll(" ", "%20");
URL sourceUrl = new URL(temp);
Encode the URL,
String url = "http://www.tonightfootballreport.com/Filebucket/Picture/image/png/20160807025619_Serie A.png";
String encodedUrl = URLEncoder.encode(url, "utf-8");
EDIT #1 :
The problem with above method as #Wai Yan Hein, pointed is that it encode all the characters in the url including the protocol.
The following code solves that issue,
String urlStr = "http://www.tonightfootballreport.com/Filebucket/Picture/image/png/20160807025619_Serie A.png";
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();
Edit #2
Alternate solution using Uri.parse,
String urlStr = "http://www.tonightfootballreport.com/Filebucket/Picture/image/png/20160807025619_Serie A.png";
String url = Uri.parse(urlStr)
.buildUpon()
.build()
.toString();
Check if the URL is indeed valid and if not try encoding it,
if(!Patterns.WEB_URL.matcher(url).matches()){
URLEncoder.encode(url, "utf-8");
//Now load via Picasso
}
else{
//Proceed with loading via picasso
}
I am writing below code to get json string from url and parse json string to get stock info in an android app. My code is given below:
url = new URL(in);
Log.e(STOCK,"comes here ..0 ");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
InputStream stream = conn.getInputStream();
String dataone = convertStreamToString(stream);
reader = new JSONObject(dataone);
Log.e(STOCK,"comes here ..1 ");
JSONObject data = reader.getJSONObject("data");
previousClose = data.getString("previousClose");
lastPrice = data.getString("lastPrice");
low52 = data.getString("low52");
totalTradedValue = data.getString("totalTradedValue");
Toast.makeText(MainActivity.this,lastPrice,Toast.LENGTH_LONG).show();
Toast.makeText(MainActivity.this,totalTradedValue,Toast.LENGTH_LONG).show();
But I am getting exception after opening url, I have added internet permission in Android Manifest xml.
In my application i need to load images from several urls into a Gridview.
The problem is that my urls contain arabic characters and images aren't downloaded.
I tested my app with English url and it's working fine, but i have problem with arabic ones.
I have tried this to decode url but it's not working:
String result = URLDecoder.decode(imageUrls.get(j), "UTF-8");
also tried this:
connection.setRequestProperty("Accept-Charset", "UTF-8");
connection.setRequestProperty("Content-Type", "text/plain; charset=utf-8");
Snippet to download bitmap:
for(j=0; j<imageUrls.size(); j++){
try {
String result = URLDecoder.decode(imageUrls.get(j), "UTF-8");
URL url=new URL(result);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("Accept-Charset", "UTF-8");
connection.setRequestProperty("Content-Type", "text/plain; charset=utf-8");
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(input);
btarray.add(bitmap);
} catch (Exception ex) {
}
}
and have
imageview.setImageBitmap(btarray.get(position));
in ImageAdapter getView method.
urls are like this:
http://www.dalass.com/1/ShowPage.php?View=252-%D9%86%D8%A7%D8%AE%D9%86-DALASS-%D8%AF%D8%A7%D9%84%D8%A7%D8%B3.jpg
somebody help please
You must use Uri.encode(String)
//String result = URLDecoder.decode(imageUrls.get(j), "UTF-8");
String result = Uri.encode(imageUrls.get(j));
URL url = new URL(result);
Uri uri = Uri.parse(url);
String encodeUriString = Uri.encode(uri.getLastPathSegment());
String uriString = uri.toString().replace(uri.getLastPathSegment(), encodeUriString);
Log.d(TAG, uriString);
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;