今天做項目的時候,需要向伺服器介面 傳遞 json參數,使用 apache 的 httpclient,當時沒有對參數做特殊處理直接提交了,結果運行時報錯了,如下:
06-06 10:05:40.683: W/System.err(15573): java.lang.IllegalArgumentException: Illegal character in query at index 40: http://xxxxx.com/detail/?info={"type":"1","shopid":"f436701fd5c0423db53a8047894ca4e1","fields":{"name":true,"tel":true,"scores":true,"intro":true}}06-06 10:05:40.753: W/System.err(15573): at java.net.URI.create(URI.java:727)06-06 10:05:40.753: W/System.err(15573): at org.apache.http.client.methods.HttpGet.<init>(HttpGet.java:75)06-06 10:05:40.753: W/System.err(15573): at com.yulore.sdktest.http.NetUtil.get(NetUtil.java:106)06-06 10:05:40.777: W/System.err(15573): at com.yulore.sdktest.http.BaseTask.run(BaseTask.java:25)06-06 10:05:40.777: W/System.err(15573): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)06-06 10:05:40.777: W/System.err(15573): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)06-06 10:05:40.777: W/System.err(15573): at java.lang.Thread.run(Thread.java:856)
後來在網上查資料找到原因了:HttpGet或 HttpPost都不能傳包含 " 、“{"、"}"這樣的參數,需要對特殊字元進行轉義,把 " 轉成%22,把 { 轉成%7b,把 } 轉成%7d
RequestVo reqVo = new RequestVo();reqVo.context = getApplicationContext();StringBuffer sb = new StringBuffer();sb.append("?info={\"type\":\"1\",");sb.append("\"shopid\":\"" + shopId + "\",");sb.append("\"fields\":{\"name\":true,");sb.append("\"address\":true,");sb.append("\"tel\":true,");sb.append("\"scores\":true,");sb.append("\"intro\":true}}");String param = sb.toString().replace("\"", "%22").replace("{", "%7b").replace("}", "%7d");//特殊字元進行轉義reqVo.requestUrl = getString(R.string.detail_api).concat(param);reqVo.jsonParser = new ShopParser();BaseTask task = new BaseTask(getApplicationContext(), reqVo,handler);ThreadPoolManager.getInstance().addTask(task);
注意:參數裡面如果有 空格的話,也需要轉義,否則會有問題。