android httpclient and utf-8

坚强是说给别人听的谎言 提交于 2019-12-18 12:43:11

问题


I'm trying to connect to a webservice where my querysting holds some data. The bad thing is that this data contains utf-8 charcters, which renders a problem.

If I simply call HttpGet with the ordinary string I get the "illegal character" exception. So I googled and tried some utf-8 magic.

            HttpClient httpclient = new DefaultHttpClient();
        httpclient.getParams().setParameter("http.protocol.content-charset", "UTF-8");
        String utfurl = URLEncoder.encode(url, "utf-8");
        HttpGet httpGet = new HttpGet(utfurl);
        HttpResponse response = httpclient.execute(httpGet);
        content = response.getEntity().getContent();
            } catch (Exception e) {
                Log.d(TAG, "getInputStream: " +e.getMessage());

Now I won't get the illegal charcter, but it seem to mess upp the utfurl completely since I instead get the "target host must not be null, or set in parameters". Probably because he doesnt recognize the "http://" part in a messed up string. Any advice?

Regards


回答1:


I think you want a URL encoded query string. If so, use:

String query = "?param=value";
String host = "http://my.host.name.com/";
String encodedUrl = host + UrlEncoder.encode(query,"utf-8");

The basic idea is that you only want to encode the query string, not the host name or protocol.



来源:https://stackoverflow.com/questions/4989743/android-httpclient-and-utf-8

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!