3

I have the following JSON:

{
  "category": [{
    "id": "90",
    "user_id": "1",
    "category_id": "27",
    "name": "આણંદ કોમર્સિયલ લેયર",
    "order": "0",
    "created_at": "2014-05-03 17:09:54",
    "updated_at": "2014-05-03 17:09:54",
    "deleted": "0",
    "subtopics": [{
      "id": "203",
      "user_id": "1",
      "category_id": "27",
      "subcategory_id": "90",
      "name": "આણંદ કોમર્સિયલ લેયર (સંકર જાત)",
      "order": "0",
      "details": "<p style=\"text-align:justify\"><img alt=\"\" src=\"/packages/wysiwyg/ckeditor/plugins/kcfinder/upload/images/1.png\" style=\"height:271px; width:237px\" /></p>\r\n\r\n<ul>\r\n\t<li style=\"text-align:justify\">પ્રથમ ઈંડું મુક્વાની સરેરાશ ઉંમર:૧૪૨ દિવસ</li>\r\n\t<li style=\"text-align:justify\">સરેરાશ વાર્ષિક ઈંડા ઉત્પાદન : ૩૦૦ ઈંડા</li>\r\n\t<li style=\"text-align:justify\">૪૦ અઠવાડીયાની ઉંમરે ઈંડાનું સરેરાશ વજન : ૫૨ ગ્રામ</li>\r\n\t<li style=\"text-align:justify\">૭૨ અઠવાડીયાની ઉંમરે ઈંડાનું સરેરાશ વજન : ૫૪ ગ્રામ</li>\r\n\t<li style=\"text-align:justify\">સારી જીવાદોરી</li>\r\n</ul>\r\n",
      "mobile_detail": "<p style=\"text-align:justify\"><img alt=\"\" src=\"/packages/wysiwyg/ckeditor/plugins/kcfinder/upload/images/1.png\" style=\"height:271px; width:237px\" /></p>\r\n\r\n<ul>\r\n\t<li style=\"text-align:justify\">પ્રથમ ઈંડું મુક્વાની સરેરાશ ઉંમર:૧૪૨ દિવસ</li>\r\n\t<li style=\"text-align:justify\">સરેરાશ વાર્ષિક ઈંડા ઉત્પાદન : ૩૦૦ ઈંડા</li>\r\n\t<li style=\"text-align:justify\">૪૦ અઠવાડીયાની ઉંમરે ઈંડાનું સરેરાશ વજન : ૫૨ ગ્રામ</li>\r\n\t<li style=\"text-align:justify\">૭૨ અઠવાડીયાની ઉંમરે ઈંડાનું સરેરાશ વજન : ૫૪ ગ્રામ</li>\r\n\t<li style=\"text-align:justify\">સારી જીવાદોરી</li>\r\n</ul>\r\n",
      "created_at": "2014-05-03 17:11:43",
      "updated_at": "2014-05-11 13:41:31",
      "deleted": "0",
      "images": [],
      "videos": []
    }]
  }]
}

I have the following code:

public JSONObject getJSONFromUrl(String url) {

    // Making HTTP request
    InputStream is=null;
    try {
        // defaultHttpClient
        DefaultHttpClient httpClient = new DefaultHttpClient();
        //HttpPost httpPost = new HttpPost(url);
        HttpGet httpPost = new HttpGet(url);
        httpPost.setHeader("Content-Type", "application/json");
        httpPost.setHeader("X-Requested-With", "XMLHttpRequest");
        httpPost.setHeader("Mobile-Tokon", "7c^4N:9Y*Tq;P^f");
        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        is = httpEntity.getContent();

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    String json="";
    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8000);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        json = sb.toString();
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

    // try parse the string to a JSON object
    JSONObject jObj=null;
    try {
        jObj = new JSONObject(json);
        Log.d("JSON",jObj.toString());
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    // return JSON String
    return jObj;

}

In my Java class, I call the above function like this:

getJSONFromUrl("http://ikishan.192.168.1.87.xip.io/api/newapps/27?email=api.ikisan@aau.in&password=%~?7ON9Xjp;BcYu");

I get an error:

java.lang.IllegalArgumentException: Invalid % sequence: %~? in query at index 83: http://ikishan.192.168.1.87.xip.io/api/newapps/27?email=api.ikisan@aau.in&password=%~?7ON9Xjp;BcYu

At this line:

HttpGet httpPost = new HttpGet(url);

Any idea how I can solve this?

EDIT

image

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Harshal Kalavadiya
  • 2,412
  • 4
  • 38
  • 71

2 Answers2

2

That's because the URL that you've mentioned is not a valid URL as specified in this SO answer.

a complete URL is always in its encoded form: you take the strings for the individual components (scheme, authority, path, etc.), encode each according to its own rules, and then combine them into the complete URL string. Trying to build a complete unencoded URL string and then encode it separately leads to subtle bugs, like spaces in the path being incorrectly changed to plus signs (which an RFC-compliant server will interpret as real plus signs, not encoded spaces).

Those invalid characters that are mentioned in IllegalArgumentException exception should not be directly sent with GET request and needs to be converted into this format

Character   From Windows-1252   From UTF-8
  %               %25               %25
  ~               %7E               %7E
  ?               %3F               %3F

see this url for complete list


In Java, the correct way to build a URL is with the URI class.

import java.net.URLEncoder;

public class HelloWorld {
    static String uri = "http://ikishan.192.168.1.87.xip.io/api/newapps/27";
    static String params = "?email=api.ikisan@aau.in&password=%~?7ON9Xjp;BcYu";

     public static void main(String []args){
        try {
            String encodedParams = URLEncoder.encode( params, "ASCII" ).toString();
            System.out.println(uri + encodedParams);
        }
        catch(java.io.UnsupportedEncodingException uee) {
            //do something
        }
     }
}

Output

http://ikishan.192.168.1.87.xip.io/api/newapps/27%3Femail%3Dapi.ikisan%40aau.in%26password%3D%25%7E%3F7ON9Xjp%3BBcYu
Community
  • 1
  • 1
Raman Sahasi
  • 30,180
  • 9
  • 58
  • 71
1

Try like below. if you encrypct password then you can do like below .

// Encrypt Password to UTF-8 format

private String encrypt(String pwd) {
    String encryptedPwd = null;
    try {
        byte[] byteArray = pwd.getBytes("UTF-8");
        encryptedPwd = Base64.encodeToString(byteArray, Base64.DEFAULT).trim();
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    return encryptedPwd;
}

you can Encode URL with below class

public class EncodingUtil{


 /**
 * Decodes the passed UTF-8 String using an algorithm that's compatible with
 * JavaScript's <code>decodeURIComponent</code> function. Returns
 * <code>null</code> if the String is <code>null</code>.
 *
 * @param s The UTF-8 encoded String to be decoded
 * @return the decoded String
 */
public static String decodeURIComponent(String s)
{
    if (s == null)
    {
        return null;
    }

    String result = null;

    try
    {
        result = URLDecoder.decode(s, "UTF-8");
    }

    // This exception should never occur.
    catch (UnsupportedEncodingException e)
    {
        result = s;
    }

    return result;
}

/**
 * Encodes the passed String as UTF-8 using an algorithm that's compatible
 * with JavaScript's <code>encodeURIComponent</code> function. Returns
 * <code>null</code> if the String is <code>null</code>.
 *
 * @param s The String to be encoded
 * @return the encoded String
 */
public static String encodeURIComponent(String s)
{
    String result = null;

    try
    {
        result = URLEncoder.encode(s, "UTF-8")
                .replaceAll("\\+", "%20")
                .replaceAll("\\%21", "!")
                .replaceAll("\\%27", "'")
                .replaceAll("\\%28", "(")
                .replaceAll("\\%29", ")")
                .replaceAll("\\%7E", "~");
    }

    // This exception should never occur.
    catch (UnsupportedEncodingException e)
    {
        result = s;
    }

    return result;
}

/**
 * Private constructor to prevent this class from being instantiated.
 */
private EncodingUtil()
{
    super();
}}
Vishal Thakkar
  • 2,117
  • 2
  • 16
  • 33