Android错误连接到远程服务器上的数据库

时间:2019-02-12 05:25:05

标签: php mysql android-studio

我正在尝试将我的android应用程序连接到远程服务器上的数据库。 我创建了一个登录表单,但显示以下错误。


02/11 21:14:24: Launching app
No apk changes detected since last installation, skipping installation of C:\Users\manav\AndroidStudioProjects\MySQLConnect\app\build\outputs\apk\debug\app-debug.apk
$ adb shell am force-stop com.example.mysqlconnect
$ adb shell am start -n "com.example.mysqlconnect/com.example.mysqlconnect.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER
Connected to process 31621 on device xiaomi-redmi_note_3-dbdeee7e
Capturing and displaying logcat messages from application. This behavior can be disabled in the "Logcat output" section of the "Debugger" settings page.
W/System: ClassLoader referenced unknown path: /data/app/com.example.mysqlconnect-1/lib/arm64
D/AccessibilityManager: current package=com.example.mysqlconnect, accessibility manager mIsFinalEnabled=false, mOptimizeEnabled=false, mIsUiAutomationEnabled=false, mIsInterestedPackage=false
D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true
I/Adreno: QUALCOMM build                   : a7823f5, I59a6815413
    Build Date                       : 09/23/16
    OpenGL ES Shader Compiler Version: XE031.07.00.00
    Local Branch                     : mybranch22028469
    Remote Branch                    : quic/LA.BR.1.3.3_rb2.26
    Remote Branch                    : NONE
    Reconstruct Branch               : NOTHING
I/OpenGLRenderer: Initialized EGL, version 1.4
E/HAL: hw_get_module_by_class: module name gralloc
    hw_get_module_by_class: module name gralloc
I/Timeline: Timeline: Activity_launch_request time:71856102
D/OpenGLRenderer: endAllStagingAnimators on 0x559d757b20 (RippleDrawable) with handle 0x559d759ed0
I/DpmTcmClient: RegisterTcmMonitor from: com.android.okhttp.TcmIdleTimerMonitor
D/OpenGLRenderer: endAllStagingAnimators on 0x559d874d50 (RippleDrawable) with handle 0x559d89f8a0
W/System.err: javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.
        at com.android.org.conscrypt.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:328)
        at com.android.okhttp.internal.http.SocketConnector.connectTls(SocketConnector.java:103)
        at com.android.okhttp.Connection.connect(Connection.java:143)
        at com.android.okhttp.Connection.connectAndSetOwner(Connection.java:185)
W/System.err:     at com.android.okhttp.OkHttpClient$1.connectAndSetOwner(OkHttpClient.java:128)
        at com.android.okhttp.internal.http.HttpEngine.nextConnection(HttpEngine.java:342)
        at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:331)
        at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:249)
        at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:437)
        at com.android.okhttp.internal.huc.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:114)
        at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:245)
        at com.android.okhttp.internal.huc.DelegatingHttpsURLConnection.getOutputStream(DelegatingHttpsURLConnection.java:218)
        at com.android.okhttp.internal.huc.HttpsURLConnectionImpl.getOutputStream(HttpsURLConnectionImpl.java:25)
        at com.example.mysqlconnect.BackgroundTask.doInBackground(BackgroundTask.java:52)
        at com.example.mysqlconnect.BackgroundTask.doInBackground(BackgroundTask.java:23)
        at android.os.AsyncTask$2.call(AsyncTask.java:295)
        at java.util.concurrent.FutureTask.run(FutureTask.java:237)
        at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
        at java.lang.Thread.run(Thread.java:818)
    Caused by: java.security.cert.CertificateException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.
W/System.err:     at com.android.org.conscrypt.TrustManagerImpl.checkTrusted(TrustManagerImpl.java:324)
        at com.android.org.conscrypt.TrustManagerImpl.checkServerTrusted(TrustManagerImpl.java:225)
        at com.android.org.conscrypt.Platform.checkServerTrusted(Platform.java:115)
        at com.android.org.conscrypt.OpenSSLSocketImpl.verifyCertificateChain(OpenSSLSocketImpl.java:556)
        at com.android.org.conscrypt.NativeCrypto.SSL_do_handshake(Native Method)
        at com.android.org.conscrypt.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:324)
        ... 20 more
    Caused by: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.
W/System.err:   ... 26 more
V/BoostFramework: BoostFramework() : mPerf = com.qualcomm.qti.Performance@b7340e
V/BoostFramework: BoostFramework() : mPerf = com.qualcomm.qti.Performance@b19e2f
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.mysqlconnect, PID: 31621
    android.view.WindowManager$BadTokenException: Unable to add window -- token android.os.BinderProxy@965df6d is not valid; is your activity running?
        at android.view.ViewRootImpl.setView(ViewRootImpl.java:584)
        at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:313)
        at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:86)
        at android.app.Dialog.show(Dialog.java:322)
        at com.example.mysqlconnect.BackgroundTask.onPostExecute(BackgroundTask.java:134)
        at com.example.mysqlconnect.BackgroundTask.onPostExecute(BackgroundTask.java:23)
        at android.os.AsyncTask.finish(AsyncTask.java:651)
        at android.os.AsyncTask.access$500(AsyncTask.java:180)
        at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:668)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:157)
        at android.app.ActivityThread.main(ActivityThread.java:5604)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:774)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:652)
I/Process: Sending signal. PID: 31621 SIG: 9
Application terminated.

以下是我的Java文件。

MainActivity.java

package com.example.mysqlconnect;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;

public class MainActivity extends Activity {
    EditText ET_NAME,ET_PASS;
    String login_name,login_pass;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ET_NAME = (EditText)findViewById(R.id.user_name);
        ET_PASS = (EditText)findViewById(R.id.user_pass);
    }

    public void userReg(View view) {
        startActivity(new Intent(this,Register.class));
    }

    public void userLogin(View view) {
        login_name = ET_NAME.getText().toString();
        login_pass = ET_PASS.getText().toString();
        String method = "login";
        BackgroundTask backgroundTask = new BackgroundTask(this);
        backgroundTask.execute(method,login_name,login_pass);
    }
}

BackgroundTask.java

public class BackgroundTask extends AsyncTask<String,Void,String> {
    AlertDialog alertDialog;
    Context ctx;

    BackgroundTask(Context ctx) {
        this.ctx =ctx;
    }

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

    @Override
    protected String doInBackground(String... params) {
        String reg_url = "https://snipy.unaux.com/MySQLDemo/register.php";
        String login_url = "https://snipy.unaux.com/MySQLDemo/login.php";
        String method = params[0];

        if (method.equals("register")) {
            String name = params[1];
            String user_name = params[2];
            String user_pass = params[3];
            try {
                URL url = new URL(reg_url);
                HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                httpURLConnection.setRequestMethod("POST");
                httpURLConnection.setDoOutput(true);

                //httpURLConnection.setDoInput(true);
                OutputStream OS = httpURLConnection.getOutputStream();
                BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(OS, "UTF-8"));
                String data = URLEncoder.encode("user", "UTF-8") + "=" + URLEncoder.encode(name, "UTF-8") + "&" +
                        URLEncoder.encode("user_name", "UTF-8") + "=" + URLEncoder.encode(user_name, "UTF-8") + "&" +
                        URLEncoder.encode("user_pass", "UTF-8") + "=" + URLEncoder.encode(user_pass, "UTF-8");
                bufferedWriter.write(data);
                bufferedWriter.flush();
                bufferedWriter.close();
                OS.close();
                InputStream IS = httpURLConnection.getInputStream();
                IS.close();
                //httpURLConnection.connect();
                httpURLConnection.disconnect();
                String string= new String("Registration Success...");

                return string;
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else if(method.equals("login")) {
            String login_name = params[1];
            String login_pass = params[2];
            try {
                URL url = new URL(login_url);
                HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
                httpURLConnection.setRequestMethod("POST");
                httpURLConnection.setDoOutput(true);
                httpURLConnection.setDoInput(true);
                OutputStream outputStream = httpURLConnection.getOutputStream();
                BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream,"UTF-8"));
                String data = URLEncoder.encode("login_name","UTF-8")+"="+URLEncoder.encode(login_name,"UTF-8")+"&"+
                    URLEncoder.encode("login_pass","UTF-8")+"="+URLEncoder.encode(login_pass,"UTF-8");
                bufferedWriter.write(data);
                bufferedWriter.flush();
                bufferedWriter.close();
                outputStream.close();

                InputStream inputStream = httpURLConnection.getInputStream();
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
                String response = "";
                String line  = "";
                while ((line = bufferedReader.readLine()) != null) {
                    response+= line;
                }
                bufferedReader.close();
                inputStream.close();
                httpURLConnection.disconnect();

                return response;
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

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

    @Override
    protected void onPostExecute(String result) {
        if (result =="Registration Success...") {
            Toast.makeText(ctx, result, Toast.LENGTH_LONG).show();
        } else {
            alertDialog.setMessage(result);
            alertDialog.show();
        }
    }
}

Register.java

package com.example.mysqlconnect;

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

public class Register extends Activity {
    EditText ET_NAME,ET_USER_NAME,ET_USER_PASS;
    String name,user_name,user_pass;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.register_layout);

        ET_NAME = (EditText)findViewById(R.id.name);
        ET_USER_NAME= (EditText)findViewById(R.id.new_user_name);
        ET_USER_PASS = (EditText)findViewById(R.id.new_user_pass);
    }

    public void userReg(View view) {
        name = ET_NAME.getText().toString();
        user_name = ET_USER_NAME.getText().toString();
        user_pass =ET_USER_PASS.getText().toString();
        String method = "register";
        BackgroundTask backgroundTask = new BackgroundTask(this);
        backgroundTask.execute(method,name,user_name,user_pass);
        finish();
    }
}

请帮忙...我在这里呆了很长时间,如果您能提供有关如何使用MySQL和PHP将android应用程序连接到服务器上的数据库的任何资源,那将是非常值得的。

2 个答案:

答案 0 :(得分:0)

https://snipy.unaux.com/

该网站的ssl证书不受系统信任。

您可以根据okhttp doc信任您的证书。

或者您也可以将http替换为https来解决此问题。

字符串reg_url =“ http://snipy.unaux.com/MySQLDemo/register.php”;

字符串login_url =“ http://snipy.unaux.com/MySQLDemo/login.php”;

答案 1 :(得分:0)

检查网址是否为http或https,然后将连接从http更改为https:

URL url = new URL(reg_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();

if (reg_url.startsWith("https://") {
    SSLSocketFactory socketFactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
    ((HttpsURLConnection) httpURLConnection).setSSLSocketFactory(socketFactory);
}

httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);

对登录执行相同的操作。