java.net.ConnectException: 无法连接到 /10.0.2.2:443

huangapple go评论115阅读模式
英文:

java.net.ConnectException:Failed to connect to /10.0.2.2:443

问题

以下是翻译好的部分:

我正在开发一个需要用户认证的 Android 应用程序。我正在使用 localhost 的 phpadmin 用于服务器和数据库连接。到目前为止,该应用程序只有一个登录活动,它导入一个 PHP URL 来连接到 localhost。如果一切正常,该应用程序应该显示一个 alertDialog,表示登录成功。但是,无论我尝试运行应用程序时,当我点击登录时,它都会显示一个空的 alertDialog,并且 Android Studio 的调试器显示以下错误:java.net.ConnectException: Failed to connect to /10.0.2.2:443

这是 MainActivity 的代码:

package com.android.example.meetmev0;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity {
    EditText UsernameEt, PasswordEt;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        UsernameEt = (EditText) findViewById(R.id.editTextTextPersonName);
        PasswordEt = (EditText) findViewById(R.id.editTextTextPassword);
    }

    public void OnLogin(View view) {
        String username = UsernameEt.getText().toString();
        String password = PasswordEt.getText().toString();
        BackroundWorker backroundWorker = new BackroundWorker(this);
        String type = "login";
        backroundWorker.execute(type, username, password);
    }
}

这是 BackroundWorker 类的代码:

package com.android.example.meetmev0;

import android.app.AlertDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;

import javax.net.ssl.HttpsURLConnection;

public class BackroundWorker extends AsyncTask<String, Void, String> {
    Context context;
    AlertDialog alertDialog;

    public BackroundWorker(Context ctx) {
        context = ctx;
    }

    @Override
    protected String doInBackground(String... voids) {
        String type = voids[0];
        String login_url = "https://10.0.2.2/MeetLogin.php";
        if (type.equals("login")) {
            try {
                String username = voids[1];
                String password = voids[2];
                URL url = new URL(login_url);
                HttpsURLConnection httpsURLConnection = (HttpsURLConnection) url.openConnection();
                httpsURLConnection.setRequestMethod("POST");
                httpsURLConnection.setDoOutput(true);
                httpsURLConnection.setDoInput(true);
                OutputStream outputStream = httpsURLConnection.getOutputStream();
                BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
                String post_data = URLEncoder.encode("username", "UTF-8") + "=" + URLEncoder.encode(username, "UTF-8") + "&"
                        + URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(password, "UTF-8");
                bufferedWriter.write(post_data);
                bufferedWriter.flush();
                bufferedWriter.close();
                outputStream.close();
                InputStream inputStream = httpsURLConnection.getInputStream();
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "ISO-8859-1"));
                String result = "";
                String line = "";
                while ((line = bufferedReader.readLine()) != null) {
                    result += line;
                }
                bufferedReader.close();
                inputStream.close();
                httpsURLConnection.disconnect();
                Log.v("Activity test:", result);
                return result;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    @Override
    protected void onPreExecute() {
        alertDialog = new AlertDialog.Builder(context).create();
        alertDialog.setTitle("Login Status");
    }

    @Override
    protected void onPostExecute(String result) {
        alertDialog.setMessage(result);
        alertDialog.show();
    }

    @Override
    protected void onProgressUpdate(Void... values) {
        super.onProgressUpdate(values);
    }
}

通过设置断点,我发现这一行 OutputStream outputStream = httpsURLConnection.getOutputStream(); 抛出了异常。

这是我的 AndroidManifest 文件:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.android.example.meetmev0">
    <uses-permission android:name="android.permission.INTERNET"></uses-permission>
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme"
        android:usesCleartextTraffic="true">

        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

我尝试添加端口 80、8080 和 8888,但没有成功。将 10.0.2.2 替换为 localhost 或我的本地 IP 也不起作用。

英文:

I am working on an android app that requires user authentication. I am using localhost phpadmin for server and database connexion. The app so far has 1 login activity that imports a php url to connect to localhost. If everything works fine the app is supposed to show an alertDialog saying that login was successful. But whenever i try running the app, when i click login it shows an empty alertDialog and the AndroidStudio debugger shows this error : java.net.ConnectException:Failed to connect to /10.0.2.2:443

This is the code for MainActivity :


import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
EditText UsernameEt , PasswordEt;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
UsernameEt= (EditText)findViewById(R.id.editTextTextPersonName);
PasswordEt= (EditText)findViewById(R.id.editTextTextPassword);
}
public void OnLogin(View view) {
String username= UsernameEt.getText().toString();
String password= PasswordEt.getText().toString();
BackroundWorker backroundWorker=new BackroundWorker(this);
String type= &quot;login&quot;;
backroundWorker.execute(type,username,password);
}
} 

and this is the code for BackroundWorker class:

package com.android.example.meetmev0;
import android.app.AlertDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import javax.net.ssl.HttpsURLConnection;
public class BackroundWorker extends AsyncTask&lt;String,Void,String&gt; {
Context context;
AlertDialog alertDialog;
public BackroundWorker ( Context ctx) {
context=ctx;
}
@Override
protected String doInBackground(String... voids) {
String type = voids[0];
String login_url= &quot;https://10.0.2.2/MeetLogin.php&quot;;
if(type.equals(&quot;login&quot;))
{
String test=&quot;so far so good&quot;;
try {
String username = voids[1];
String password = voids[2];
URL url= new URL(login_url);
HttpsURLConnection httpsURLConnection = (HttpsURLConnection)url.openConnection();
httpsURLConnection.setRequestMethod(&quot;POST&quot;);
httpsURLConnection.setDoOutput(true);
httpsURLConnection.setDoInput(true);
OutputStream outputStream= httpsURLConnection.getOutputStream();
test= &quot; still good&quot;;
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, &quot;UTF-8&quot;));
String post_data= URLEncoder.encode(&quot;username &quot;, &quot;UTF-8&quot;)+&quot;=&quot;+URLEncoder.encode(username , &quot;UTF-8&quot;)+&quot;&amp;&quot;
+URLEncoder.encode(&quot;password&quot;, &quot;UTF-8&quot;)+&quot;=&quot;+URLEncoder.encode(password , &quot;UTF-8&quot;);
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpsURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,&quot;ISO-8859-1&quot;));
String result=&quot;&quot;;
String line=&quot;&quot;;
while((line = bufferedReader.readLine())!=null){
result+=line;
}
bufferedReader.close();
inputStream.close();
httpsURLConnection.disconnect();
Log.v(&quot;Activity test: &quot;, result);
return result;
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
@Override
protected void onPreExecute() {
alertDialog= new AlertDialog.Builder(context).create();
alertDialog.setTitle(&quot;Login Status&quot;);
}
@Override
protected void onPostExecute(String result) {
alertDialog.setMessage(result);
alertDialog.show();
}
@Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}

using breakpoints i found out that this line
OutputStream outputStream= httpsURLConnection.getOutputStream();
is what's throwing the exception.

This is my AndroidManifest file :

&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;manifest xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
package=&quot;com.android.example.meetmev0&quot;&gt;
&lt;uses-permission android:name=&quot;android.permission.INTERNET&quot;&gt;&lt;/uses-permission&gt;
&lt;application
android:allowBackup=&quot;true&quot;
android:icon=&quot;@mipmap/ic_launcher&quot;
android:label=&quot;@string/app_name&quot;
android:roundIcon=&quot;@mipmap/ic_launcher_round&quot;
android:supportsRtl=&quot;true&quot;
android:theme=&quot;@style/AppTheme&quot;
android:usesCleartextTraffic=&quot;true&quot;&gt;
&lt;activity android:name=&quot;.MainActivity&quot;&gt;
&lt;intent-filter&gt;
&lt;action android:name=&quot;android.intent.action.MAIN&quot; /&gt;
&lt;category android:name=&quot;android.intent.category.LAUNCHER&quot; /&gt;
&lt;/intent-filter&gt;
&lt;/activity&gt;
&lt;/application&gt;
&lt;/manifest&gt;

I tried adding ports 80,8080 and 8888 but it didn't work. Swapping 10.0.2.2to localhostor to my local ip didn't work either.

答案1

得分: 3

我将"https"更改为"http":

String login_url= "https://10.0.2.2/MeetLogin.php"``` 更改为 ```java String login_url= "http://10.0.2.2/MeetLogin.php"

并且

```java HttpsURLConnection httpsURLConnection = (HttpsURLConnection)url.openConnection();``` 更改为 ```java HttpURLConnection httpsURLConnection = (HttpURLConnection)url.openConnection();```

现在它正常工作

<details>
<summary>英文:</summary>

I changed https to http: 

`String login_url= &quot;https://10.0.2.2/MeetLogin.php&quot; ` to  `String login_url= &quot;http://10.0.2.2/MeetLogin.php&quot; ` 

and 

` HttpsURLConnection httpsURLConnection = (HttpsURLConnection)url.openConnection(); ` to ` HttpURLConnection httpsURLConnection = (HttpURLConnection)url.openConnection(); `

Now it works perfectly.

</details>



huangapple
  • 本文由 发表于 2020年8月25日 19:52:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/63578261.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定