获取头参数不能正常工作的方法

时间:2016-07-28 04:09:06

标签: java android utf-8

我有以下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": []
    }]
  }]
}

我有以下代码:

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;

}

在我的Java类中,我将上述函数称为:

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

我收到错误:

  

java.lang.IllegalArgumentException:无效的%序列:%〜?在索引83的查询中:http://ikishan.192.168.1.87.xip.io/api/newapps/27?email=api.ikisan@aau.in&password=%~?7ON9Xjp;BcYu

在这一行:

HttpGet httpPost = new HttpGet(url);

知道如何解决这个问题吗?

修改

image

2 个答案:

答案 0 :(得分:2)

这是因为您提到的网址不是this SO答案中指定的有效网址。

  

完整的网址始终采用编码形式:您可以使用字符串   各个组件(方案,权限,路径等)对每个组件进行编码   根据自己的规则,然后将它们组合成完整的   网址字符串。 尝试构建完整的未编码的URL字符串,然后   单独编码会导致细微的错误,就像路径中的空格一样   被错误地更改为加号(符合RFC的服务器)   将解释为真正的加号,而不是编码的空格。)

IllegalArgumentException例外中提及的无效字符不应与GET请求直接一起发送,需要转换为此格式

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

请参阅this网址以获取完整列表

在Java中,构建URL的正确方法是使用URI类。

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
        }
     }
}

<强>输出

http://ikishan.192.168.1.87.xip.io/api/newapps/27%3Femail%3Dapi.ikisan%40aau.in%26password%3D%25%7E%3F7ON9Xjp%3BBcYu

答案 1 :(得分:1)

尝试如下。如果你加密密码,那么你可以这样做。

// 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;
}

您可以使用以下类

编码网址
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();
}}