开发者

android httpclient and utf-8

开发者 https://www.devze.com 2023-02-10 13:21 出处:网络
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.

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 c开发者_运维知识库ompletely 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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号