我正在做一个Android Studio项目,有几个活动。我目前正试图从本地主机上的Java Servlet读取输出,但由于套接字权限,它似乎崩溃了。

我做了一个新项目,使用完全相同的代码,工作得很完美。所以我不明白为什么不愿意在我的项目工作。

public class LoginActivity extends AppCompatActivity {


String apiUrl = "http://10.0.2.2:8080/ProyectService/Servlet?action=login";
EditText username;
EditText password;
AlertDialog dialog;
Usuario session;

@Override
public void onCreate(Bundle savedInstanceState) {
    // Inicializacion de ventana
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);
    getSupportActionBar().hide();

    // Inicializacion de componentes
    username = findViewById(R.id.username);
    password = findViewById(R.id.password);

    // Inicializacion de funcionalidad de botones
    Button button= (Button) findViewById(R.id.login);
    button.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            UserLoginTask mAuthTask = new UserLoginTask();
            mAuthTask.execute();
        }
    });

    password = findViewById(R.id.password);
    createAlertDialog("Usuario o Contraseña Incorrectos");
    }

    private void createAlertDialog(String message){
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setMessage(message)
            .setTitle("Error");
    dialog = builder.create();
    }



    // ASYNCRONUS NETWORK PROCESS

    public class UserLoginTask extends AsyncTask<String, String, String> {

    @Override
    protected void onPreExecute() {
    }


    @Override
    protected String doInBackground(String... params) {

        // implement API in background and store the response in current variable
        String current = "";
        try {
            URL url;
            HttpURLConnection urlConnection = null;
            try {
                url = new URL(apiUrl);
                System.out.println(apiUrl);
                urlConnection = (HttpURLConnection) url
                        .openConnection();

                InputStream in = urlConnection.getInputStream();

                InputStreamReader isw = new InputStreamReader(in);

                int data = isw.read();
                while (data != -1) {
                    current += (char) data;
                    data = isw.read();
                    //System.out.print(current);

                }
                System.out.print(current);
                // return the data to onPostExecute method
                return current;

            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (urlConnection != null) {
                    urlConnection.disconnect();
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
            return "Exception: " + e.getMessage();
        }
        return current;
        }
    }

    protected void onPostExecute(String success) {
        Log.i(success, "");
       //attemptLogin();
    }
}

我期望它读取数据,但它崩溃在这一行:

InputStream in = urlConnection.getInputStream();

这是错误输出:

java.net.SocketException: socket failed: EPERM (Operation not permitted)
at java.net.Socket.createImpl(Socket.java:492)
at java.net.Socket.getImpl(Socket.java:552)
at java.net.Socket.setSoTimeout(Socket.java:1180)
at com.android.okhttp.internal.io.RealConnection.connectSocket(RealConnection.java:143)
at com.android.okhttp.internal.io.RealConnection.connect(RealConnection.java:116)
at com.android.okhttp.internal.http.StreamAllocation.findConnection(StreamAllocation.java:186)
at com.android.okhttp.internal.http.StreamAllocation.findHealthyConnection(StreamAllocation.java:128)
at com.android.okhttp.internal.http.StreamAllocation.newStream(StreamAllocation.java:97)
at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:289)
at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:232)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:465)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:411)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:248)
at com.example.controller.LoginActivity$UserLoginTask.doInBackground(LoginActivity.java:114)
at com.example.controller.LoginActivity$UserLoginTask.doInBackground(LoginActivity.java:93)
at android.os.AsyncTask$3.call(AsyncTask.java:378)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:289)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
at java.lang.Thread.run(Thread.java:919)

当前回答

我不得不从模拟器卸载应用程序,然后一切都开始工作了。我只需要AndroidManifest.xml上的以下权限

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

其他回答

首先,你需要改变你的android manifest .xml 但执行此操作后,必须卸载应用程序并再次运行它。 https://developer.android.com/training/basics/network-ops/connecting

代码如下:

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

在AndroidManifest.xml

在manifest中增加ACCESS_NETWORK_STATE权限 重新安装模拟器

我在android模拟器中也有同样的问题,即使在添加后

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

and

android:usesCleartextTraffic="true"

在我的模拟器上重新安装应用程序仍然存在问题。

AVD管理器->右击->冷启动现在

解决了我的问题,看起来,如果我们运行的应用程序最初没有添加互联网权限/ clearTextTraffic,我们可能需要冷启动,因为它存储一些缓存。

您的应用程序需要额外的权限和/或重新安装。

在<manifest>部分中为AndroidManifest.xml添加额外的权限:

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

若要重新安装,请从模拟器或物理连接设备卸载应用程序,然后再次运行。(如果添加了权限,请确保之后重新安装。)

我不得不删掉这个

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

留着这个

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