无法从android模拟器连接到localhost

时间:2017-01-03 07:19:31

标签: java api android-studio android-emulator laravel-5.3

我是Android开发的新手,我正在尝试连接到我在Android中的api。 我使用laravel Framework开发了我的api。 这里是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;
    }
}

我的api存储在localhost中。我在windows中使用xampp。 Laravel项目在8000端口上运行。 我的代码是正确的,因为我能够连接到网络上的其他api。 我能够连接到localhost但无法访问8000端口。 我尝试了许多方法,比如使用10.10.2.2,10.10.2.3。 但是得到错误

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

任何帮助表示赞赏。请帮助我,我试着这3天。

3 个答案:

答案 0 :(得分:2)

您需要使用运行Laravel项目的系统的IP地址。 Localhost只能用于连接到同一系统中的服务器。

答案 1 :(得分:0)

您可以使用SOAP作为替代方法,使用PHP中的代码连接到本地主机,而Android中的代码只需将方法调用到PHP代码即可。

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:     在这里参考你的代码     AsyncTask Android example

答案 2 :(得分:0)

而不是localhost你应该使用ip和端口号(如果有的话)。假设你的IP是10.10.2.2,你的端口是8000。那么您的网址应该是这样的:

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