I’m trying to create a connection using localhost but is giving refused Connection

Asked

Viewed 235 times

0

public static String getJsonSystem(String urlString){

    HttpURLConnection urlConnection = null;
    BufferedReader reader = null;
    String retorno = "";

    try{
        URL url = new URL(urlString);
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.connect();

        InputStream in = new BufferedInputStream(urlConnection.getInputStream());

        reader = new BufferedReader(new InputStreamReader(in));
        String line = "";
        StringBuffer buffer = new StringBuffer();

        while ((line = reader.readLine()) != null){
            buffer.append(line);
        }

        retorno = buffer.toString();


    } catch (Exception e){
        e.printStackTrace();
    }


    return retorno;
}

Here as I call the connection:

String caminho = "http://192.168.0.11/system/pages/login";
HttpConnection conexão = new HttpConnection();
String resp = conexão.getJsonSystem(caminho);

AlertDialog.Builder alerta = new AlertDialog.Builder(this);
alerta.setMessage(resp);
alerta.show();
  • Confirm that the server you want to connect is working. You can connect the server directly to the browser using this URL?

  • Check to see if you’re giving internet access on your Androidmanifest? So: <uses-permission android:name="android.permission.INTERNET" />

  • I tested the url is connecting. How much permission is already in my manifest.

  • Tooth debug your application and see which line is stopping.

1 answer

1


If you are using the emulator AVD you must use 10.0.2.2 to gain access to your computer’s localhost. As described in official documentation.

To the emulator Genymotion you must use 10.0.3.2.

--Edit

Remember to keep protocol http in the link, in your case:

"http://10.0.2.2/system/pages/login"

  • Lucas made the switch to 10.0.2.2 as I said already that I use AVD; He returned the following error: java.io.Filenotfoundexception: http://10.0.2.2/system/pages/login W/System.err: at org.apache.Harmony.luni.Internal.net.www.protocol.http.HttpURLConnectionImpl.getInputStream(Httpurlconnectionimpl.java:521)

  • @Felipe You must keep the http://, thus: http://10.0.2.2/system/pages/login, try and tell me if it worked.

  • I kept http://10.0.2.2/system/pages/login But when I tried to catch the return of the sentence in Json I didn’t convert to String ai it generated an error. Your reply was very effective I thank you very much for this help and provide me to increase my knowledge more.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.