Amalo
Amalo

Reputation: 772

Call httpconnection with encoding not working

i need to call a service get using http connection, the response contains arabic characters, but when i call it using the code below

 try {

        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");

        InputStream in = new BufferedInputStream(conn.getInputStream());
        response = IOUtils.toString(in, "UTF-8");
    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

the reponse is

1|U|����� ������|$2|L|���� �������|$3|S|���� 

I tried another solution not using Commons-io but also not working

                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            connection.setConnectTimeout(5000);
            connection.setRequestMethod("GET");
            connection.connect();
            int statusCode = connection.getResponseCode();
            //Log.e("statusCode", "" + statusCode);
            if (statusCode == 200) {
                sb = new StringBuilder();
                reader = new BufferedReader(new InputStreamReader(connection.getInputStream(),"UTF-8"));

                char[] tmp = new char[1024];
                int l;
                while((l = reader.read(tmp)) != -1) {
                    sb.append(tmp, 0, l);
                }
                //sb = buffer.toString();
            }

            connection.disconnect();
            if (sb != null)
                serverResponse = sb.toString();

Do i need to change anything from web service??? but when i call it from browser all characters show clearly with no problem any suggestion?

Upvotes: 0

Views: 334

Answers (2)

Omar Hayat
Omar Hayat

Reputation: 378

Please decode your string response

String dateStr = URLDecoder.decode(yourStringResponse, "utf-8");

Upvotes: 1

Esteban Collado
Esteban Collado

Reputation: 1910

Maybe the server is not using UTF-8, your code is trying to use UTF-8 to decode the data but that will only work if the server is using the same encoding.

The browser works because maybe it is using the HTTP header "Content-Encoding" which should indicate the encoding used for the data.

Upvotes: 3

Related Questions