Encoded URL and java.lang.IllegalArgumentException - java

I encode some URL parameters and URL becomes correct, but I still get java.lang.IllegalArgumentException. Here is my code:
StringBuilder makeUrlFromWord = new StringBuilder();
List<String> splittedUrl = mParser.splitRequest(urls[0]);
try {
makeUrlFromWord.append("http://")
.append(URLEncoder.encode(splittedUrl.get(0), HTTP.UTF_8))
.append(".jpg.to/");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
Log.d("Made url", makeUrlFromWord.toString());
Here is part of the log:
D/Made url﹕ http://%D0%BF%D1%80%D0%B8%D0%B2%D0%B5%D1%82.jpg.to/
W/System.err﹕ java.lang.IllegalArgumentException: Host name may not be null
The link is correct, I tried this in browser, it decodes back in to Cyrillic symbols and works.

It looks like the trick is to use IDNA encoding:
Android defines java.net.IDN providing the conversion functions.

That works for me. Converts "привет.jpg.to" to "http://xn--b1agh1afp.jpg.to/" thanks to #18446744073709551615
makeUrlFromWord.append("http://")
.append(IDN.toASCII(splittedUrl.get(0)))
.append(".jpg.to/");

Related

Problem with Special characters in XML conversion

I don't know why my code does not want to change special characters from XML file, such as "<" , ">" to "&lt", "&gt" ??
I saw that you need to use escapeXML method, which I did. Also, I have put complete xml code to string with FileUtils.readFileToString() method - this works fine.
Can someone helps me out - what did I do wrong?
try {
File file = new File("C:\\Users\\Desktop\\project\\src\\main\\test1.xml");
s = FileUtils.readFileToString(file, "utf-8");
StringEscapeUtils.escapeXml10(s);
} catch(Exception e) {
e.printStackTrace();
}

Convert base64 string to image at server side in java

I have base64 String which I want to convert back to image irrespective of image format at server side. I tried it by using following code, image is getting created but when I am trying to preview it, showing error could not load image.
public void convertStringToImage(String base64) {
try {
byte[] imageByteArray = decodeImage(base64);
FileOutputStream imageOutFile = new FileOutputStream("./src/main/resources/demo.jpg");
imageOutFile.write(imageByteArray);
imageOutFile.close();
} catch (Exception e) {
logger.log(Level.SEVERE, "ImageStoreManager::convertStringToImage()" + e);
}
}
public static byte[] decodeImage(String imageDataString) {
return Base64.decodeBase64(imageDataString);
}
what should I do so that my image will look properly?
Your code looks fine. I can suggest however some more debugging steps for you.
Encode your file manually using, for example, this webpage
Compare if String base64 contains exact same content like you've got seen on the page. // if something wrong here, your request is corrupted, maybe some encoding issues on the frontend side?
See file content created under ./src/main/resources/demo.jpg and compare content (size, binary comparison) // if something wrong here you will know that actually save operation is broken
Remarks:
Did you try to do .flush() before close?
Your code in current form might cause resource leakage, have a look at try-with-resources
Try this:
public static byte[] decodeImage(String imageDataString) {
return org.apache.commons.codec.binary.Base64.decodeBase64(imageDataString.getBytes());
}

URL encoding issue in java

Here is my sample url:
url.com/data?format=json&pro={%22merchanturl%22:%22http://url.com/logo.pn‌​g%22,%22price%22:599,%22productDesc%22:%22Apple%2032GBBlack%22,%22prodID%22:%2291‌​3393%22,%22merchant%22:%224536%22,%22prourl%22:%22http://url.com/data%22,%22name%‌​22:%22Apple%2032GB%20%2D%20Black%22,%22productUrl%22:%22http://www.url.com/image.‌​jpg%22,%22myprice%22:550,%22mercname%22:%22hello%22,%22mybool%22:false}
I have an android app. I need to post this url to server. So that server responds back with a token. I am doing the httppost through app. But I am not getting any response/exception. If I copy the same url and paste it in browser, that works very well. I hope I am doing mistake with the encoding part. Can anyone point out my issue?
Here is my encoding method:
private String encodeString(String input) {
String output = new String(input.trim().replace(" ", "%20")
.replace("&", "%26").replace(",", "%2c").replace("(", "%28")
.replace(")", "%29").replace("!", "%21").replace("=", "%3D")
.replace("<", "%3C").replace(">", "%3E").replace("#", "%23")
.replace("$", "%24").replace("'", "%27").replace("*", "%2A")
.replace("-", "%2D").replace(".", "%2E").replace("/", "%2F")
.replace(":", "%3A").replace(";", "%3B").replace("?", "%3F")
.replace("#", "%40").replace("[", "%5B").replace("\\", "%5C")
.replace("]", "%5D").replace("_", "%5F").replace("`", "%60")
.replace("{", "%7B").replace("|", "%7C").replace("}", "%7D")
.replace("\"", "%22"));
return output;
}
Update:
The reason why I am doing like this is, I need to send the data as in this format. The parameters part of the url is a json data. If I encode the complete url, that is not working.
Try using URLEncoder, encode only the part after ?
String query = URLEncoder.encode(queryPart, "utf-8");
String url = "http://server.com/search?q=" + query;
Although a self-written encoding isn't bad, I recommend using built-in Java methods that have been proven to be working.
TextUtils contains a method htmlEncode(String s) just for this.
http://developer.android.com/reference/android/text/TextUtils.html#htmlEncode%28java.lang.String%29

How to resolve java.net.MalformedURLException: Protocol not found: 9 in android

I am trying to load images in my android application from a url (http://www.elifeshopping.com/images/stories/virtuemart/product/thumbnail (2).jpg) using BitmapFactory the code is below :
try {
// ImageView i = (ImageView)findViewById(R.id.image);
bitmap = BitmapFactory.decodeStream((InputStream) new URL(url)
.getContent());
i.setImageBitmap(bitmap);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
here i get
05-03 15:57:13.156: W/System.err(1086): java.net.MalformedURLException: Protocol not found: 9
05-03 15:57:13.167: W/System.err(1086): at java.net.URL.<init>(URL.java:273)
05-03 15:57:13.167: W/System.err(1086):
at java.net.URL.<init>(URL.java:157).
Please help by telling what I am doing wrong.
I used
productImgUrl = productImgUrl.replaceAll(" ", "%20");
i replaced all the spaces by %20
and its working for me ..
Thanks everybody for their responses
Please help by telling what I am doing wrong.
I think that the problem is that you are calling the URL constructor with an invalid URL string. Indeed, the exception message implies that the URL string starts with "9:". (The 'protocol' component is the sequence of characters before the first colon character of the URL.)
This doesn't make a lot of sense if the URL string really is:
"http://www.elifeshopping.com/images/stories/virtuemart/product/thumbnail (2).jpg"
so I'd infer that it is ... in fact ... something else. Print it out before you call the URL constructor to find out what it really is.
(You should also %-escape the space characters in the URL's path ... but I doubt that will fix this particular exception incarnation.)
Change your url to http://www.elifeshopping.com/images/stories/virtuemart/product/thumbnail%20%282%29.jpg

How to verify that URL is valid in Java 1.6?

My application processes URLs entered manually by users. I have discovered that some of malformed URLs (like 'http:/not-valid') result in NullPointerException thrown when connection is being opened. As I learned from this Java bug report, the issue is known and will not be fixed. The suggestion is to use java.net.URI, which is "more RFC 2396-conformant".
Question is: how to use URI to work around the problem? The only thing I can do with URI is to use it to parse string and generate URL. I have prepared following program:
import java.net.*;
public class Test
{
public static void main(String[] args)
{
try {
URI uri = URI.create(args[0]);
Object o = uri.toURL().getContent(); // try to get content
}
catch(Throwable e) {
e.printStackTrace();
}
}
}
Here are results of my tests (with java 1.6.0_20), not much different from what I get with java.net.URL:
sh-3.2$ java Test url-not-valid
java.lang.IllegalArgumentException: URI is not absolute
at java.net.URI.toURL(URI.java:1080)
at Test.main(Test.java:9)
sh-3.2$ java Test http:/url-not-valid
java.lang.NullPointerException
at sun.net.www.ParseUtil.toURI(ParseUtil.java:261)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:795)
at sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:726)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1049)
at java.net.URLConnection.getContent(URLConnection.java:688)
at java.net.URL.getContent(URL.java:1024)
at Test.main(Test.java:9)
sh-3.2$ java Test http:///url-not-valid
java.lang.IllegalArgumentException: protocol = http host = null
at sun.net.spi.DefaultProxySelector.select(DefaultProxySelector.java:151)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:796)
at sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:726)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1049)
at java.net.URLConnection.getContent(URLConnection.java:688)
at java.net.URL.getContent(URL.java:1024)
at Test.main(Test.java:9)
sh-3.2$ java Test http:////url-not-valid
java.lang.NullPointerException
at sun.net.www.ParseUtil.toURI(ParseUtil.java:261)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:795)
at sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:726)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1049)
at java.net.URLConnection.getContent(URLConnection.java:688)
at java.net.URL.getContent(URL.java:1024)
at Test.main(Test.java:9)
You can use appache Validator Commons ..
UrlValidator urlValidator = new UrlValidator();
urlValidator.isValid("http://google.com");
http://commons.apache.org/validator/
http://commons.apache.org/validator/api-1.3.1/
If I run your code with the type of malformed URI in the bug report then it throws URISyntaxException. So the suggested fix fixes the reported error.
$ java -cp bin UriTest http:\\\\www.google.com\\
java.lang.IllegalArgumentException
at java.net.URI.create(URI.java:842)
at UriTest.main(UriTest.java:8)
Caused by: java.net.URISyntaxException: Illegal character in opaque part at index 5: http:\\www.google.com\
at java.net.URI$Parser.fail(URI.java:2809)
at java.net.URI$Parser.checkChars(URI.java:2982)
at java.net.URI$Parser.parse(URI.java:3019)
at java.net.URI.(URI.java:578)
at java.net.URI.create(URI.java:840)
Your type of malformed URI is different, and does not appear to be a syntax error.
Instead, catch the null pointer exception and recover with a suitable message.
You could try and be friendly and check whether the URI starts with a single slash "http:/" and suggest that to the user, or you can check whether the hostname of the URL is non-empty:
import java.net.*;
public class UriTest
{
public static void main ( String[] args )
{
try {
URI uri = URI.create ( args[0] );
// avoid null pointer exception
if ( uri.getHost() == null )
throw new MalformedURLException ( "no hostname" );
URL url = uri.toURL();
URLConnection s = url.openConnection();
s.getInputStream();
} catch ( Throwable e ) {
e.printStackTrace();
}
}
}
Note that even with the approaches proposed in the other answers, you wouldn't get validation right, since java.net.URI adheres to RFC 2396, which is notably outdated. By using java.net.URI, you'll get exceptions for URLs that today are valid for all web browsers.
In order to solve these issues, I wrote a library for URL parsing in Java: galimatias. It performs URL parsing the same way web browsers do (adhering to the WHATWG URL Specification).
In your case, you can write:
try {
URL url = io.mola.galimatias.URL.parse(url).toJavaURL();
} catch (GalimatiasParseException e) {
// If this exception is thrown, the given URL contains a unrecoverable error. That is, it's completely invalid.
}
As a nice side-effect, you get a lot of sanitization that you won't get with java.net.URI. For example, http:/example.com will be correctly parsed as http://example.com/.

Categories