3

I want to build a simple android mobile app, that will communicate through REST API with a python-Flask server -

So the android client will run on my Sumsung Galaxy J7 Prime phone (using USB connection through an android-studio script which runs on my computer), and the python-Flask server will run on my computer (using running python-Flask file through PyCharm workspace).

All i want to do is to pass a simple message between those client and server, with a regular connection (not localhost).

This is the simple server code:

from flask import Flask
app = Flask(__name__)

@app.route("/RESTfulExample/json/product/get")
def hello():
    return "Hello World !!"

if __name__ == "__main__":
    app.run(host='0.0.0.0', debug=True)

This code works well when i run this server, and enter the URL address with google chrome URL: http://127.0.0.1:5000/RESTfulExample/json/product/get

It works fine also when I run a script in Jave which sends this URL to the server (with localhost communication):

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class firstJava {

    public static void main(String[] args) {

      try {

        URL url = new URL("http://localhost:5000/RESTfulExample/json/product/get");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Accept", "application/json");

        if (conn.getResponseCode() != 200) {
            throw new RuntimeException("Failed : HTTP error code : "
                    + conn.getResponseCode());
        }

        BufferedReader br = new BufferedReader(new InputStreamReader(
            (conn.getInputStream())));

        String output;
        System.out.println("Output from Server .... \n");
        while ((output = br.readLine()) != null) {
            System.out.println(output);
        }

        conn.disconnect();

      } catch (MalformedURLException e) {

        e.printStackTrace();

      } catch (IOException e) {

        e.printStackTrace();

      }

    }

}

The output is:

Output from Server .... 

Hello World !!

The problem comes when i use the exact same code in the my andriod-studio project, except of changing the IP address from localhost(127.0.0.1) to the IP of my computer (10.0.0.54):

public void buttonClicked (View view){

        EditText editText = (EditText) findViewById(R.id.passwordEditText);
        try {

            URL url = new URL("http://10.0.0.54:5000/RESTfulExample/json/product/get");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setRequestProperty("Accept", "application/json");

            System.out.println(conn.getResponseCode());
            if (conn.getResponseCode() != 200) {
                throw new RuntimeException("Failed : HTTP error code : "
                        + conn.getResponseCode());
            }

            BufferedReader br = new BufferedReader(new InputStreamReader(
                    (conn.getInputStream())));

            String output;
            System.out.println("Output from Server .... \n");
            while ((output = br.readLine()) != null) {
                editText.setText(output);
            }

            conn.disconnect();

        } catch (MalformedURLException e) {

            e.printStackTrace();

        } catch (IOException e) {

            e.printStackTrace();

        }

}

When I run this script in android studio, the application in my phone collapses, and in the console in the android-studio, the error lines are those:

I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.example.owner.firstapp, PID: 25703
                  java.lang.IllegalStateException: Could not execute method for android:onClick
                      at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:293)
                      at android.view.View.performClick(View.java:5721)
                      at android.widget.TextView.performClick(TextView.java:10931)
                      at android.view.View$PerformClick.run(View.java:22620)
                      at android.os.Handler.handleCallback(Handler.java:739)
                      at android.os.Handler.dispatchMessage(Handler.java:95)
                      at android.os.Looper.loop(Looper.java:148)
                      at android.app.ActivityThread.main(ActivityThread.java:7409)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
                   Caused by: java.lang.reflect.InvocationTargetException
                      at java.lang.reflect.Method.invoke(Native Method)
                      at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
                      at android.view.View.performClick(View.java:5721) 
                      at android.widget.TextView.performClick(TextView.java:10931) 
                      at android.view.View$PerformClick.run(View.java:22620) 
                      at android.os.Handler.handleCallback(Handler.java:739) 
                      at android.os.Handler.dispatchMessage(Handler.java:95) 
                      at android.os.Looper.loop(Looper.java:148) 
                      at android.app.ActivityThread.main(ActivityThread.java:7409) 
                      at java.lang.reflect.Method.invoke(Native Method) 
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230) 
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120) 
                   Caused by: android.os.NetworkOnMainThreadException
                      at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1273)
                      at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:110)
                      at libcore.io.IoBridge.connectErrno(IoBridge.java:137)
                      at libcore.io.IoBridge.connect(IoBridge.java:122)
                      at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:183)
                      at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:452)
                      at java.net.Socket.connect(Socket.java:884)
                      at com.android.okhttp.internal.Platform.connectSocket(Platform.java:117)
                      at com.android.okhttp.internal.http.SocketConnector.connectRawSocket(SocketConnector.java:438)
                      at com.android.okhttp.internal.http.SocketConnector.connectCleartext(SocketConnector.java:105)
                      at com.android.okhttp.Connection.connect(Connection.java:1333)
                      at com.android.okhttp.Connection.connectAndSetOwner(Connection.java:1412)
                      at com.android.okhttp.OkHttpClient$1.connectAndSetOwner(OkHttpClient.java:131)
                      at com.android.okhttp.internal.http.HttpEngine.nextConnection(HttpEngine.java:485)
                      at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:466)
                      at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:372)
                      at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:476)
                      at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:418)
                      at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponseCode(HttpURLConnectionImpl.java:540)

                      at com.example.owner.firstapp.MainActivity.buttonClicked(MainActivity.java:44)

                      at java.lang.reflect.Method.invoke(Native Method) 
                      at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288) 
                      at android.view.View.performClick(View.java:5721) 
                      at android.widget.TextView.performClick(TextView.java:10931) 
                      at android.view.View$PerformClick.run(View.java:22620) 
                      at android.os.Handler.handleCallback(Handler.java:739) 
                      at android.os.Handler.dispatchMessage(Handler.java:95) 
                      at android.os.Looper.loop(Looper.java:148) 
                      at android.app.ActivityThread.main(ActivityThread.java:7409) 
                      at java.lang.reflect.Method.invoke(Native Method) 
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230) 
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120) 
I/Process: Sending signal. PID: 25703 SIG: 9
Application terminated.

As the separated line above tells, the problem is with line 44 - System.out.println(conn.getResponseCode()); which means, that for some reason, the conn.getResponseCode() isn't work.

So i understand that the problem occures when i stop use the localhost connection and move to a regular connection between 2 devices. I just don't know how to fix it.

I didn't know i will stuck so much time with a simple server-client communication.. I will glad if someone here will help me solve this simple problem.

Thank you very much in advance, and sorry for my bad english :)

1 Answer 1

1

I know you posted this few months ago, but have you thought enabling internet permissions in your manifest file ?

Sign up to request clarification or add additional context in comments.

2 Comments

I have already fixed it up.. It was about the code - i had to use "asynctask". thanks anyway !!
I guessed you had fixed it haha ! Well yeah sorry, i didn't see the "NetworkOnMainThreadException" exception... which was caught because too much "work" was done on the main thread (so yes, using asyntask or new Thread() solves this problem)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.