Java http get/post 傳遞json參數問題__大資料

來源:互聯網
上載者:User

今天做項目的時候,需要向伺服器介面 傳遞 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);



注意:參數裡面如果有 空格的話,也需要轉義,否則會有問題。





相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.