Sending Json via android GET

0

Problem in special characters ( keys, parentheses, etc. ) that contains a json that I'm sending via GET . The android generates the following log:

> E/AndroidRuntime(1956): java.lang.IllegalArgumentException: Illegal
> character in path at index 61:
> http://10.0.3.2:8084/meuapp/recurso/objeto/download/{}

My GET method is as follows

public static String GET(Context context, String endereco){
        //Verifica se existe conexão com a internet
        if(!existeConexao(context))
            return K.FALHA_CONEXAO;
        InputStream inputStream = null;
        HttpClient httpClient = new DefaultHttpClient();
        String result = K.FALHA;
        try{
            HttpGet httpGet = new HttpGet(endereco);//A excessão acontece aqui
            HttpResponse httpResponse = httpClient.execute(httpGet);
            inputStream = httpResponse.getEntity().getContent();
            if(inputStream!=null){
                //Converte resposta do WebService para String
                result = inputStreamParaString(inputStream);
            }else
                result = K.FALHA;
        }catch(UnsupportedEncodingException e){
            e.printStackTrace();
        }catch(ClientProtocolException e){
            e.printStackTrace();
        }catch(IOException e){
            e.printStackTrace();
        }


        return result;
    }
    
asked by anonymous 20.11.2014 / 12:56

1 answer

2

In general URI's are defined by RFC 3986 (Section 2 - Characters ) and may contain the following characters:

ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~:/?#[]@!$&'()*+,;=

The rest need to be encoded in the format

%hh

And since the JSON format has the { and } character, which are invalid, I recommend using the URLEncoder.encode :

JSONObject objetoJSON = new JSONObject();

// Popula seu json com as propriedades

String url = caminho.concat(URLEncoder.encode(objetoJSON.toString(), "UTF-8"));

And instead of having something like:

http://10.0.3.2:8084/meuapp/recurso/objeto/download/{"chave1": "valor1", "chave2": "valor2"}

It will have something like:

http://10.0.3.2:8084/meuapp/recurso/objeto/download/%7B%22chave1%22%3A%20%22valor1%22%2C%20%22chave2%22%3A%20%22valor2%22%7D

References

  • link
  • link
  • 20.11.2014 / 13:47