Search code examples
androidhttpserversocket

HTTP Post in Android to an emulator instance


My requirement is I have an emulator listening on port 5001. How can I do a HTTP Post to this port from another instance of my emulator? What should be the URL? When I tried URL like, 10.0.2.15:5001, am getting exceptions(No response and target server failed to respond).

Also, even when I have the serversocket listening in a separate thread, am getting ANR exception. Please let me know if I have to do port re-direction or port forwarding.

Any example link/tutorial would be helpful(as I couldnt find one). Thanks in advance!


Solution

  • try this ....

    private class WriteToServer extends AsyncTask<Double, Void, Void> {
    
            private final String serverip = "10.0.2.15";
            private final int serverport = 5001;
            Socket s;
            private DataOutputStream dos = null;
    
            @Override
            protected Void doInBackground(Double... params) {
    
                try {
    
                    // open the stream
                    s = new Socket("10.0.2.15", 5001);
                    dos = new DataOutputStream(s.getOutputStream());
    
                    // write the passed double to the stream
                    dos.writeDouble(params[0]);
                    dos.flush();
    
                } catch (Exception e) {
                    Log.i("AsyncTank", "something's gone wrong");
                }
    
                return null;
            }
    

    for more info check... http://developer.android.com/reference/android/os/AsyncTask.html