Problem when showing a json from my localhost

1

I am developing a app in which I want to connect said app to a api . But I'm having problems receiving the json to be able to show it within my app . I share the code.

MainActivity

public class MainActivity extends Activity {

    EditText etResponse;
    TextView tvIsConnected;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // get reference to the views
        etResponse = (EditText) findViewById(R.id.etResponse);
        tvIsConnected = (TextView) findViewById(R.id.tvIsConnected);

        // check if you are connected or not
        if(isConnected()){
            tvIsConnected.setBackgroundColor(0xFF00CC00);
            tvIsConnected.setText("You are conncted");
        }
        else{
            tvIsConnected.setText("You are NOT conncted");
        }

        // call AsynTask to perform network operation on separate thread
        new HttpAsyncTask().execute("http://localhost/usuario/");
    }

    public static String GET(String url){
        InputStream inputStream = null;
        String result = "";
        try {

            // create HttpClient
            HttpClient httpclient = new DefaultHttpClient();

            // make GET request to the given URL
            HttpResponse httpResponse = httpclient.execute(new HttpGet(url));

            // receive response as inputStream
            inputStream = httpResponse.getEntity().getContent();

            // convert inputstream to string
            if(inputStream != null)
                result = convertInputStreamToString(inputStream);
            else
                result = "Did not work!";

        } catch (Exception e) {
            Log.d("InputStream", e.getLocalizedMessage());
        }

        return result;
    }

    private static String convertInputStreamToString(InputStream inputStream) throws IOException{
        BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
        String line = "";
        String result = "";
        while((line = bufferedReader.readLine()) != null)
            result += line;

        inputStream.close();
        return result;

    }

    public boolean isConnected(){
        ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Activity.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
        if (networkInfo != null && networkInfo.isConnected())
            return true;
        else
            return false;
    }
    private class HttpAsyncTask extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... urls) {

            return GET(urls[0]);
        }
        // onPostExecute displays the results of the AsyncTask.
        @Override
        protected void onPostExecute(String result) {
            Toast.makeText(getBaseContext(), "Received!", Toast.LENGTH_LONG).show();
            etResponse.setText(result);

        }
    }
}

Activity_main

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/tvIsConnected"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:background="#FF0000"
        android:textColor="#FFF"
        android:textSize="18dp"
        android:layout_marginBottom="5dp"
        android:text="is connected? " />

    <EditText
        android:id="@+id/etResponse"
        android:layout_width="match_parent"
        android:layout_height="fill_parent"
        android:ems="10"
        android:layout_marginTop="10dp"
        android:inputType="textMultiLine" >\
        <requestFocus />
    </EditText>
</LinearLayout>

The json q I try to show in my app

    
asked by Germanccho 29.01.2018 в 15:23
source

2 answers

2

Hello the problem you have is an IP addressing issue, localhost is a reserved name that all computers have, mouse or device regardless of whether or not you have an ethernet network card. The name localhost is translated as the IP address of loopback 127.0.0.1 in IPv4, or as the address: 1 in IPv6.1

In summary this line is wrong the URL

new HttpAsyncTask().execute("http://localhost/usuario/");

Unless the server is running from the device. In general for the rest of the devices in a local network the IPv4 of your team is usually of this style 192.168.x.x , you can find it easily in the following way:

Windows, open cmd or powershell and type:

ipconfig

Linux

ifconfig

This will show you the local IP of your PC, an example in windows

IPv4 address is the IP of the PC that you will have to place, Gateway is the IP of the router.

    
answered by 29.01.2018 / 15:38
source
1

When you type localhost , the DNS will search the local machine for the indicated resource. This local device represents your device and the most likely thing is that the API is installed on another machine, not on your smartphone. In other words, when you search on your device: /localhost/usuario/ , you are trying to connect to your own android device looking for the resource /usuario/ .

To achieve what you want you have to indicate the IP where the API is installed. Where the api is installed, run the cmd and type the ipconfig command in the Wireless Lan Adapter Wifi -> IPv4 option:

Wireless LAN adapter Wi-Fi:

   Connection-specific DNS Suffix  . : Home
   Link-local IPv6 Address . . . . . : fe80::611d:8046:c32b:991b%14
   IPv4 Address. . . . . . . . . . . : 192.168.1.5 <--------- Aqui estaria la IP que reemplazarias por localhost
   Subnet Mask . . . . . . . . . . . : 255.255.255.0
   Default Gateway . . . . . . . . . : 192.168.1.1

As you probably have already noticed, the pc where you have the API installed must be connected to the same network of your device, whether it is Wi-Fi if it is with a physical device or LAN if it is with an emulator, but the Android device does not You can find this resource.

To buy the same network, open the browser of your device and write the ip of the machine where the api is installed, if you find it, it will show you the IIS / APACHE information or any http server, otherwise you will have that create a connection between the two.

    
answered by 29.01.2018 в 15:37