通过Android模拟器连接到10.0.2.2时,我陷入了加载页面

时间:2019-03-15 18:20:50

标签: android-studio xampp

我正在将Xampp与android模拟器一起使用。当它设置为连接到给定的URL时,它将继续加载并无法连接到数据库。有人帮忙。

我尝试过:

http://localhost/
http://10.0.2.2:8080/
http://10.0.2.2/

我的网址看起来像

"https://10.0.2.2/users/register.php";

这是 mainactivity.java 文件。

package com.example.androidregisterandlogin;

import android.app.DownloadManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONException;
import org.json.JSONObject;

import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Map;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import static com.android.volley.Request.*;

public class RegisterActivity extends AppCompatActivity {

public EditText name,email,password,c_password;
public Button btn_regist;
public ProgressBar loading;
public static String URL_REGIST = "https://10.0.2.2/users/register.php";

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


    new NukeSSLCerts().nuke();



    loading = findViewById(R.id.loading);
    name = findViewById(R.id.name);
    email = findViewById(R.id.email);
    password = findViewById(R.id.password);
    c_password = findViewById(R.id.c_password);
    btn_regist = findViewById(R.id.btn_regist);

    btn_regist.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Regist();
        }
    });
}
public static class NukeSSLCerts {
    protected static final String TAG = "NukeSSLCerts";

    public static void nuke() {
        try {
            TrustManager[] trustAllCerts = new TrustManager[] {
                    new X509TrustManager() {
                        public X509Certificate[] getAcceptedIssuers() {
                            X509Certificate[] myTrustedAnchors = new X509Certificate[0];
                            return myTrustedAnchors;
                        }

                        @Override
                        public void checkClientTrusted(X509Certificate[] certs, String authType) {}

                        @Override
                        public void checkServerTrusted(X509Certificate[] certs, String authType) {}
                    }
            };

            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, trustAllCerts, new SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
            HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String arg0, SSLSession arg1) {
                    return true;
                }
            });
        } catch (Exception e) {
        }
    }
}

public void Regist(){

    loading.setVisibility(View.VISIBLE);
    btn_regist.setVisibility(View.GONE);

    final String name=this.name.getText().toString().trim();
    final String email=this.email.getText().toString().trim();
    final String password=this.password.getText().toString().trim();

    StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_REGIST,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                try{

                    JSONObject jsonObject = new JSONObject(response);
                    String success = jsonObject.getString("success");

                    if (success.equals("1")){
                        Toast.makeText(RegisterActivity.this, "Register Success", Toast.LENGTH_SHORT).show();
                    }

                } catch (JSONException e) {
                    Log.i("tagconvertstr", "hello");
                    e.printStackTrace();
                    Toast.makeText(RegisterActivity.this, "Register Error! " + e.toString(),Toast.LENGTH_SHORT).show();
                    loading.setVisibility(View.GONE);
                    btn_regist.setVisibility(View.VISIBLE);
                }
                }
            },

            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Toast.makeText(RegisterActivity.this, "Register Error! " + error.toString(),Toast.LENGTH_SHORT).show();
                    loading.setVisibility(View.GONE);
                    btn_regist.setVisibility(View.VISIBLE);
                }
            })


    {
        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
            Map<String, String> params = new HashMap<>();
            params.put("name", name);
            params.put("email", email);
            params.put("password", password);
            return params;
        }
    };

    RequestQueue requestQueue = Volley.newRequestQueue(this);
    requestQueue.add(stringRequest);

    }
}

activity.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingLeft="30dp"
android:paddingRight="30dp"
android:paddingTop="80dp"
tools:context=".RegisterActivity">

<android.support.design.widget.TextInputLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    tools:layout_editor_absoluteX="30dp"
    tools:layout_editor_absoluteY="20dp">
    <EditText
        android:id="@+id/name"
        android:hint="Name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textPersonName" />
</android.support.design.widget.TextInputLayout>

<android.support.design.widget.TextInputLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    tools:layout_editor_absoluteX="30dp"
    tools:layout_editor_absoluteY="84dp">

    <EditText
        android:id="@+id/email"
        android:layout_marginTop="10dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Email"
        android:inputType="textEmailAddress" />
</android.support.design.widget.TextInputLayout>


<android.support.design.widget.TextInputLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:passwordToggleEnabled="true"
    tools:layout_editor_absoluteX="30dp"
    tools:layout_editor_absoluteY="148dp">

    <EditText
        android:id="@+id/password"
        android:layout_marginTop="10dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Password"
        android:inputType="textPassword" />
</android.support.design.widget.TextInputLayout>


<android.support.design.widget.TextInputLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:passwordToggleEnabled="true"
    tools:layout_editor_absoluteX="30dp"
    tools:layout_editor_absoluteY="212dp">

    <EditText
        android:id="@+id/c_password"
        android:layout_marginTop="10dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Confirm Password"
        android:inputType="textPassword" />
</android.support.design.widget.TextInputLayout>

<ProgressBar
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:visibility="gone"
    android:layout_marginTop="30dp"
    android:id="@+id/loading" />

<Button
    android:text="REGISTER"
    android:id="@+id/btn_regist"
    android:layout_marginTop="30dp"
    android:backgroundTint="@color/colorPrimary"
    android:textColor="@android:color/white"
    android:layout_width="match_parent"
    android:layout_height="55dp" />

manifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.androidregisterandlogin">

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

<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">
    <activity android:name=".RegisterActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <action android:name="android.intent.action.VIEW"/>
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
      </activity>
    </application>

 </manifest>

connect.php

<?php

    $conn = mysqli_connect("localhost","root","","users");

?>

register.php

<?php

if ($_SERVER['REQUEST_METHOD'] =='POST'){


   require_once 'connect.php';

   $name = $_POST['name'];
   $email = $_POST['email'];
   $password = $_POST['password'];

   $password = password_hash($password, PASSWORD_DEFAULT);

   $sql = "INSERT INTO users_table (name, email, password) VALUES ('$name', 
  '$email', '$password')";

   if ( mysqli_query($conn, $sql) ) {
      $result["success"] = "1";
      $result["message"] = "success";

    echo json_encode($result);
    mysqli_close($conn);

   } else {

    $result["success"] = "0";
    $result["message"] = "error";

    echo json_encode($result);
    mysqli_close($conn);
  }
}

?>

0 个答案:

没有答案