简体   繁体   English

无法从安卓模拟器连接到本地主机

[英]Not able to connect to localhost from android emulator

I am new to android development , I am trying to connect to my api in android .我是 android 开发的新手,我试图在 android 中连接到我的 api。 I have developed my api using laravel Framework .我已经使用 laravel Framework 开发了我的 api。 Here Login.java这里Login.java

package com.example.yasha.myapplication;

import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.ExecutionException;

import android.util.Log;

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

import javax.net.ssl.HttpsURLConnection;

public class Login extends AppCompatActivity {

    EditText emailText;
    EditText passwordText ;
    TextView signup;
    Button loginButton ;

    @Override
    public void onCreate(Bundle savedInstanceState) {


        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

         emailText = (EditText) findViewById(R.id.email);
         passwordText = (EditText) findViewById(R.id.password);
         signup = (TextView) findViewById(R.id.signup);
         loginButton = (Button) findViewById(R.id.login);

        signup.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // Start the Signup activity
                Intent signupIntent = new Intent(getApplicationContext(), SignUp.class);
                startActivity(signupIntent);
            }
        });


    }

    public class MakeAccessToken extends AsyncTask<String, Void, String> {

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

            String result = "";
            URL url;
            HttpURLConnection urlConnection = null;

            try {
                url = new URL(urls[0]);

                urlConnection = (HttpURLConnection) url.openConnection();
                urlConnection.setRequestMethod("POST");
                InputStream in = urlConnection.getInputStream();

                InputStreamReader reader = new InputStreamReader(in);

                int data = reader.read();

                while (data != -1) {

                    char current = (char) data;

                    result += current;

                    data = reader.read();

                }

                //int responseCode = urlConnection.getResponseCode();
                //if(responseCode == HttpsURLConnection.HTTP_OK){
                    return result;
                //}else{
                //    return "Wrong Creditinal";
                // }

            } catch (IOException e) {
                e.printStackTrace();
            }

            return null;
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            Log.i("Access Token", result);
        }
    }

    public void login(View view) {

        if (!validate()) {
            onLoginFailed();
            return;
        }
        final String email = emailText.getText().toString();
        final String password = passwordText.getText().toString();

        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
        final int client_id = prefs.getInt("client_id", 1);
        final String client_secret = prefs.getString("client_secret", " ");


        loginButton.setEnabled(false);

        final ProgressDialog progressDialog = new ProgressDialog(this);
        progressDialog.setIndeterminate(true);
        progressDialog.setMessage("Verifying...");
        progressDialog.show();

        // TODO: Implement your own authentication logic here.
        new android.os.Handler().postDelayed(
                new Runnable() {
                    public void run() {
                        MakeAccessToken task = new MakeAccessToken();
                        task.execute("http://10.0.2.3:8000/oauth/token?grant_type=password&client_id="+client_id+"&client_secret="+client_secret+"&username="+email+"&password="+password);
                    }
                }, 3000);

    }



    public void onLoginSuccess() {
        loginButton.setEnabled(true);
        Intent profileIntent = new Intent(getApplicationContext(), Profile.class);
        startActivity(profileIntent);
    }

    public void onLoginFailed() {
        Toast.makeText(getBaseContext(), "Login failed", Toast.LENGTH_LONG).show();

        loginButton.setEnabled(true);
    }

    public boolean validate() {
        boolean valid = true;

        String email = emailText.getText().toString();
        String password = passwordText.getText().toString();

        if (email.isEmpty() || !android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
            emailText.setError("enter a valid email address");
            valid = false;
        } else {
            emailText.setError(null);
        }

        if (password.isEmpty() || password.length() < 4 || password.length() > 10) {
            passwordText.setError("between 4 and 10 alphanumeric characters");
            valid = false;
        } else {
            passwordText.setError(null);
        }

        return valid;
    }
}

My api is running in localhost .我的 api 在 localhost 中运行。 I am using xampp in windows .我在 windows 中使用 xampp 。 Laravel project run on the 8000 port. Laravel 项目运行在 8000 端口。 My code is right as i am able to connect to other api on web .我的代码是正确的,因为我能够连接到网络上的其他 api。 I am able to connect to localhost but not able to access the 8000 port .我能够连接到 localhost 但无法访问 8000 端口。 I have tried many methods like using 10.10.2.2 , 10.10.2.3 .我尝试了很多方法,比如使用 10.10.2.2 、 10.10.2.3 。 But getting error但得到错误

java.net.ConnectException: failed to connect to /10.0.2.2 (port 8000): connect failed: ETIMEDOUT

Any help appreciated .任何帮助表示赞赏。 Please help me , I am trying to do this for 3 days .请帮助我,我正在尝试这样做 3 天。

You'll need to use ip address of the system where your Laravel project is running.您需要使用运行 Laravel 项目的系统的 IP 地址。 Localhost can only be used to connect to a server within same system.本地主机只能用于连接到同一系统内的服务器。

You can have an alternative as SOAP with this having your code in PHP connect to your localhost and your code in android just calls the method to your PHP code.您可以使用 SOAP 的替代方法,将 PHP 中的代码连接到本地主机,而您在 android 中的代码只调用 PHP 代码的方法。

in PHP code:在 PHP 代码中:

<?php   
class service{      
    public function getUser(){
        $user = "root";`enter code here`
        $pass = "";
        $database = "";
        $server = "localhost";
        $mysqli = new mysqli($server,$user,$pass,$database);
        $vquery = "Your query here";                
        //<Your code in iterating the data you can put it as JSON >
        $mysqli->close();
        return $<return JSON user data>;
    }   
}   
$server = new SoapServer(null, array(
'uri' => "urn://<url>",
'soap_version' => SOAP_1_2)
);              
$server->setClass("service");     
$server->handle(); 
?>

IN ANDROID: refer your code here AsyncTask Android example在 ANDROID 中:在此处引用您的代码AsyncTask Android 示例

Instead of localhost you should use ip along with port number if any.如果有的话,您应该使用 ip 和端口号而不是localhost Say your ip is 10.10.2.2 and your port is 8000 .假设您的 ip 是10.10.2.2并且您的端口是8000 Then your URL should be something like this:那么你的 URL 应该是这样的:

http://10.10.2.2:8000/Android%20studio/myapplication/loginScript.php http://10.10.2.2:8000/Android%20studio/myapplication/loginScript.php

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM