HttpHostConnectionException - Android

1

I made% with a simple Visual Studio Community 2013 to register a person and receive a person, and I'm trying to consume this service with an android app, I'm emulating the application with the Web API emulator. Home When it does Genymotion it brings me an exception HttpResponse response = httpClient.execute(method); saying that the connection to HttpHostConnectionException was refused. Home The code snippet is all ok, but if you want to:

        protected String doInBackground(String... params)
        {
            HttpClient httpClient = new DefaultHttpClient();
            HttpUriRequest method = null;
            Gson gson = new Gson();

            try {
                if (metodo.toUpperCase() == "POST")
                {
                    HttpPost post = new HttpPost(url);
                    post.setEntity(new ByteArrayEntity(gson.toJson(object).getBytes()));

                    method = post;
                    method.setHeader("Content-Type", "application/json");
                }

                method.setHeader("Accept", "application/json");
                method.setHeader("Accept-Charset", "utf-8");

                HttpResponse response = httpClient.execute(method);

                status = response.getStatusLine().getStatusCode();

                return EntityUtils.toString(response.getEntity());
            }

I have already been in the documentation and checked the localhost part, and even changing from Emulator Networking to localhost it still does not work, but when I change to 10.0.2.2 it brings me that the connection has exceeded the time limit and not that it was refused.

How to proceed?

    
asked by anonymous 12.01.2015 / 21:54

3 answers

1

Try to open the api from the genymotion browser using the ip network inderezo (something like 192.168.x.x)

    
13.01.2015 / 03:31
1

If you are referring to a localhost of your device use http://10.0.2.2/ instead of http://127.0.0.1/ or http://localhost / .

Because your Android emulator is running on a virtual machine (QEMU) and you can not connect to a server running directly on your PC.

So your url should look like this:

HttpPost post = new HttpPost("http://10.0.2.2:8080/SOMENTE_EXEMPLO_QUALQUER");

Another thing, check if in your xml there is this permission:

<uses-permission android:name="android.permission.INTERNET" />
    
13.01.2015 / 03:23
1

Have you tried using the HttpUrlConnection ? Home I'll paste here a class I made for testing, using the HttpUrlConnection that sent an XML to a WebService SOAP. Home I believe the principle is the same ... you will execute a POST in your WebService and receive a return. The way the files are handled you can adapt. I would recommend testing to adapt this code - even if it is a bit dirty and experimental - to test if it is not a question in the implementation of HttpClient / HttpUrlConnection that I did ... I tried to run the APP on a device on the network and test? As I do not know how GSon works, I'm not sure if you can adapt it completely to this form but sometimes it's good to test a totally different code, it might help you find what is causing you this problem. Hope it helps.
This code was based on another stackoverflow question in English, but unfortunately I could not find the link to paste here.

    //Variaveis globais
    public static final String link = "http:\www.webservice.domain.com.br/webserviceEtc"; //Url do webservice
    private String xmlHeader; //String para o xml a ser enviado
    private String retorno; //Retorno para gravar no xml a saida

    @Override
    protected void doInBackground(Object[] params) {
        //Recebendo a string/xml que sera repassada ao webservice - Primeiro parametro obrigatorio do AsyncWebCall
        xmlHeader = params[0].toString();
        //Chamando o metodo WebServiceConnection, que exige o o xml a ser enviado ao webservice, e devolve a resposta obtida
        retorno = WebServiceConnection(xmlHeader);
    }

    /*
    * Executado após o doInBackground terminar
    * */
    @Override
    protected void onPostExecute(String result) {
        //Altera o texto do TextView, passando o retorno devolvido pelo webservice
        textView.setText(retorno);
        super.onPostExecute(result);
    }


    /*
    * Função que trata a conexão com o webservice, envia o xml e retorna a resposta
    * */
    private String WebServiceConnection(String xmlString) {

        //Declaração de variaveis
        String retorno = ""; //String que recebera o retorno do xml de resposta do webservice
        InputStream responseInputStream = null; //Carrega a String que sera transformada em arquivo xml para enviar ao webservice
        OutputStream requestOutputStream = null; //Recebe a String/xml de retorno do site
        HttpURLConnection httpURLConnection = null; //Usado para criar a conexão da requisição

        try {
            //Declaração de variaveis
            String inputLine; //Usado para escrever

            //Tenta criar uma url com a string 'link' declarada no inicio desta classe
            URL url = new URL(link); //

            // Configurando a url para o envio da requisição
            httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setConnectTimeout(15000);
            httpURLConnection.setRequestProperty("Accept-Charset", "UTF-8");
            httpURLConnection.setRequestProperty("Content-Type", "text/xml");

            // Enviando request
            requestOutputStream = httpURLConnection.getOutputStream();
            requestOutputStream.write(xmlString.getBytes("UTF-8"));

            //Recebe o retorno do webservice para ser tratadoa
            responseInputStream = httpURLConnection.getInputStream();

            //Cria um leitor para a string/xml retornada pelo site
            BufferedReader in = new BufferedReader(new InputStreamReader(responseInputStream));

            //Loop para pegar as informações lidas pelo buffer
            while ((inputLine = in.readLine()) != null) {
                retorno = inputLine; //Repassando as informações lidas do buffer, para a string que sera o retorno
                System.out.println(inputLine);
            }
            in.close(); //Fechando o buffer de leitura do xml
            System.out.println("AsyncCallWS: WebServiceConnection: " + retorno);
            return retorno;

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (SocketTimeoutException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "Erro";
    }
}
    
13.01.2015 / 07:57