android httpclient and utf-8

2020-02-26 03:03发布

问题:

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.