【问题标题】:Android to Wamp Server Connection using Android Studio and PHP使用 Android Studio 和 PHP 的 Android 到 Wamp 服务器连接
【发布时间】:2015-12-01 12:19:30
【问题描述】:

我是这里的新手。我想将我的 android 应用程序连接到 wampserver 数据库。我在这个link 上找到了一个教程,但是我应该在 wampserver 中的哪里找到我的 serverUrl?它应该是这样的:private final String serverUrl = "your path here" 那么我在哪里可以找到"your path here"

这是我的代码:

MainActivity.java

package inducesmile.com.androidloginandregistration;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;


public class MainActivity extends ActionBarActivity {

    protected EditText username;
    private EditText password;
    protected String enteredUsername;
    private final String serverUrl = "your path here";

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

        username = (EditText)findViewById(R.id.username_field);
        password = (EditText)findViewById(R.id.password_field);
        Button loginButton = (Button)findViewById(R.id.login);
        Button registerButton = (Button)findViewById(R.id.register_button);

        loginButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                enteredUsername = username.getText().toString();
                String enteredPassword = password.getText().toString();

                if(enteredUsername.equals("") || enteredPassword.equals("")){
                    Toast.makeText(MainActivity.this, "Username or password must be filled", Toast.LENGTH_LONG).show();
                    return;
                }
                if(enteredUsername.length() <= 1 || enteredPassword.length() <= 1){
                    Toast.makeText(MainActivity.this, "Username or password length must be greater than one", Toast.LENGTH_LONG).show();
                    return;

                // request authentication with remote server4
                AsyncDataClass asyncRequestObject = new AsyncDataClass();
                asyncRequestObject.execute(serverUrl, enteredUsername,     enteredPassword);

            }
        });

        registerButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this,         RegisterActivity.class);
                startActivity(intent);
            }
        });
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
        return true;
        }

        return super.onOptionsItemSelected(item);
    }
    private class AsyncDataClass extends AsyncTask<String, Void, String> {

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

            HttpParams httpParameters = new BasicHttpParams();
            HttpConnectionParams.setConnectionTimeout(httpParameters, 5000);
            HttpConnectionParams.setSoTimeout(httpParameters, 5000);

            HttpClient httpClient = new DefaultHttpClient(httpParameters);
            HttpPost httpPost = new HttpPost(params[0]);

            String jsonResult = "";
            try {
                List<NameValuePair> nameValuePairs = new     ArrayList<NameValuePair>(2);
                nameValuePairs.add(new BasicNameValuePair("username", params[1]));
                nameValuePairs.add(new BasicNameValuePair("password", params[2]));
                httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

                HttpResponse response = httpClient.execute(httpPost);
                jsonResult = inputStreamToString(response.getEntity().getContent()).toString();

            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return jsonResult;
        }
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }
        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            System.out.println("Resulted Value: " + result);
        if(result.equals("") || result == null){
            Toast.makeText(MainActivity.this, "Server connection failed", Toast.LENGTH_LONG).show();
            return;
        }
        int jsonResult = returnParsedJsonObject(result);
        if(jsonResult == 0){
            Toast.makeText(MainActivity.this, "Invalid username or password", Toast.LENGTH_LONG).show();
            return;
        }
        if(jsonResult == 1){
            Intent intent = new Intent(MainActivity.this, LoginActivity.class);
            intent.putExtra("USERNAME", enteredUsername);
            intent.putExtra("MESSAGE", "You have been successfully login");
            startActivity(intent);
        }
    }
    private StringBuilder inputStreamToString(InputStream is) {
        String rLine = "";
        StringBuilder answer = new StringBuilder();
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        try {
            while ((rLine = br.readLine()) != null) {
                answer.append(rLine);
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return answer;
    }
}
private int returnParsedJsonObject(String result){

    JSONObject resultObject = null;
    int returnedResult = 0;
    try {
        resultObject = new JSONObject(result);
        returnedResult = resultObject.getInt("success");
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return returnedResult;
}
}

我将 WampServer 与 user="root"password="" 一起使用

【问题讨论】:

  • 你现在的问题没有多大意义。如果您有特定的问题,但您在博客文章或网站中读到的内容,您可能想在此处作为评论提出。
  • 但是先生,我也评论了那里,没有回应..那里的其他用户也有同样的问题......我只想知道serverUrl来自哪里......我不知道路径..请帮帮我先生..
  • 如果您仔细观察,您会发现您发布的代码中没有任何对 serverUrl 的引用。
  • 对不起先生,我粘贴了错误的活动,它在 MainActivity.java 先生,看看我编辑的帖子.. 请我真的需要知道路径,我在 wamp 上创建了数据库,并且我在 www 目录上有 php 文件..

标签: php android mysql


【解决方案1】:

感谢 @e4c5(提供建议)并感谢 @Laser 提供答案。

我解决了!

所以对于其他会偶然发现这个问题的人,检查一下! ^_^

转到 cmd >> 输入 ipconfig >> 然后查看 IPv4 地址...

然后粘贴到private final String serverUrl = "your path here"

your path here 替换为http://192.168.1.8/android_user_api/index.php

谢谢你们!

编码愉快!

【讨论】:

    【解决方案2】:

    “路径”可能是您本地 Web 服务器的 URL,即:

    http://your_ip/your_path_to_your_php_script

    【讨论】:

    • 是 index.php 先生吗?
    • 先生,我收到此错误:org.apache.http.conn.HttpHostConnectException: Connection to localhost denied
    • 如果您在网络上。运行 ipconfig 以获取您的 IP 地址。在您的 android 应用程序中使用该 ip 从您的模拟器访问您的网络服务器。您还需要在您的网络服务器中使用 PHP 登录脚本来处理身份验证。
    • 谢谢先生,它解决了我的问题..非常感谢!
    【解决方案3】:

    您需要找到您计算机的 IPV4 地址,在您的计算机中运行命令提示符(转到 Windows 开始按钮并启动 typig cmd)并输入 ipconfig 并输入以查看您计算机的 IPV4 地址。

    在您的计算机上成功运行 WAMP 服务器表示系统托盘上有一个绿色图标,单击该图标,然后弹出菜单单击 在线 项。等待几秒钟以处理其任务。

    要在您的 android studio 模拟器中测试您的应用程序的 PHP MySQL,只需输入地址为http:\\IP Address\,然后在代码中输入您的 PHP 文件的路径。

    例如:http:\\192.168.1.7\test\example.php

    【讨论】:

      【解决方案4】:

      对我有用的解决方案是在我正在开发的 android 应用程序中使用 10.0.2.2 作为 ip 地址。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-11-08
        • 1970-01-01
        • 2012-04-28
        • 2021-08-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多