intrepidkarthi
intrepidkarthi

Reputation: 3102

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.

Upvotes: 0

Views: 3296

Answers (2)

Nermeen
Nermeen

Reputation: 15973

Try using URLEncoder, encode only the part after ?

String query = URLEncoder.encode(queryPart, "utf-8");
String url = "http://server.com/search?q=" + query;

Upvotes: 3

Qkyrie
Qkyrie

Reputation: 939

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

Upvotes: 0

Related Questions