Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
317 views
in Technique[技术] by (71.8m points)

java - Android connection to localhost

I'm trying to connect my android application to a local host url thanks to wamp server but it doesn't work. My goal here, is to fetch json data and parse these data. For my test, i'm using a device not the emulator and i use permission in AndroidManifest.xml :

<uses-permission android:name="android.permission.INTERNET" />

My url looks like this :

String url = "http://10.0.2.2:8080/tests/PhpProject1/connectionBDD.php";

i tried :

http://localhost/
http://10.0.2.2:8080/
http://10.0.2.2/

But it never worked so far :

    java.net.ConnectException: failed to connect to localhost/127.0.0.1 (port 80): connect failed: ECONNREFUSED (Connection refused)

    failed to connect to /10.0.2.2 (port 8080): connect failed: ETIMEDOUT (Connection timed out)

    java.net.ConnectException: failed to connect to /10.0.2.2 (port 80): connect failed: ETIMEDOUT (Connection timed out)

Then i tried with a json url test found on the internet : http://headers.jsontest.com/

It worked really good and i got json data at this address. So i guess my code is good and the issue here is my localhost url, i don't know what should be its exact form.. I read many threads about it but i didn't find a solution.

Here my code :

Main activity :

public class MainActivity extends Activity {
    private String url = "http://10.0.2.2:8080/tests/PhpProject1/connectionBDD.php";

    private ListView lv = null;
    private Button bGetData;

    @Override
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final JsonDownloaderTask task = new JsonDownloaderTask(this);
        lv = (ListView) findViewById(R.id.list);

        bGetData = (Button)findViewById(R.id.getdata);
        bGetData.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {               
                task.execute(url);                      
            }
        });
    }

    public void jsonTaskComplete(JSONArray data){
        //todo
    }   
}

AsyncTask :

public class JsonDownloaderTask extends AsyncTask<String, String, JSONArray> {

    MainActivity ma;

    public JsonDownloaderTask(MainActivity main){
        ma = main;
    }

    @Override
    protected JSONArray doInBackground(String... url) {
        JSONParser jParser = new JSONParser();
        // Getting JSON from URL
        JSONArray jsonArray = null;
        try {
            jsonArray = jParser.getJSONFromUrl(url[0]);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return jsonArray;        
    }

    protected void onPostExecute(JSONArray data){

        ma.jsonTaskComplete(data);
    }
}

JSONParser :

public class JSONParser {
    String data = "";
    JSONArray jsonArray = null;        
    InputStream is = null;

    public JSONParser(){}

    // Method to download json data from url
    public JSONArray getJSONFromUrl(String strUrl) throws IOException{
        try{
            URL url = new URL(strUrl);

            // Creating an http connection to communicate with url
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

            // Connecting to url
            urlConnection.connect();

            // Reading data from url
            is = urlConnection.getInputStream();

            BufferedReader br = new BufferedReader(new InputStreamReader(is));

            StringBuffer sb  = new StringBuffer();

            String line = "";
            while( ( line = br.readLine())  != null){
                sb.append(line);
            }
            is.close();
            data = sb.toString();

            //br.close();

            jsonArray = new JSONArray(data);

        }catch(Exception e){
            Log.d("Exception while downloading url", e.toString());
        }finally{
            is.close();
        }

        return jsonArray;
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

IP-address 10.0.2.2 is used to fetch data from the emulator. Localhost will always point to the emulator/android device running the application. To let your device fetch data from your pc, it should be in the same network (connected by WiFi to your router) and you should use the local IP-address of your pc (normally a 192.168.1.x-number).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...