简体   繁体   English

PHP对来自Android的HTTP请求的响应

[英]PHP Response to HTTP Request From Android

I've searched alot to find a way to send HTTP Response to Android Application that sends HTTP Request with Username and Password 我已经搜索了很多,以找到一种方法将HTTP响应发送到Android应用程序,该应用程序发送带有用户名和密码的HTTP请求

My problem is I want to take the username and password from android application and send back the values for that user from 3 columns (toggle1,toggle2,toggle3) in the database 我的问题是我想从android应用程序中获取用户名和密码,并从数据库中的3列(toggle1,toggle2,toggle3)发回该用户的值

All examples I've seen now only send 1 or 0 just for checking username and password if it's correct or not but I need to send also Columns Data from Database, I Prefer it's not JSON 我现在看到的所有例子只发送1或0只是为了检查用户名和密码,如果它是正确的,但我需要从数据库发送列数据,我更喜欢它不是JSON

Activity that sends HTTP Request and Also reads data 发送HTTP请求并且还读取数据的活动

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;

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

public class HttpLogin extends Activity {
    /** Called when the activity is first created. */
    private Button login;
    private EditText username, password;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        login = (Button) findViewById(R.id.login);
        username = (EditText) findViewById(R.id.username);
        password = (EditText) findViewById(R.id.password);

        login.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                String   mUsername = username.getText().toString();
                String  mPassword = password.getText().toString();

                tryLogin(mUsername, mPassword);
            }
        });
    }

    protected void tryLogin(String mUsername, String mPassword)
    {           
        HttpURLConnection connection;
       OutputStreamWriter request = null;

            URL url = null;   
            String response = null;         
            String parameters = "username="+mUsername+"&password="+mPassword;   

            try
            {
                url = new URL("your login URL");
                connection = (HttpURLConnection) url.openConnection();
                connection.setDoOutput(true);
                connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                connection.setRequestMethod("POST");    

                request = new OutputStreamWriter(connection.getOutputStream());
                request.write(parameters);
                request.flush();
                request.close();            
                String line = "";               
                InputStreamReader isr = new InputStreamReader(connection.getInputStream());
                BufferedReader reader = new BufferedReader(isr);
                StringBuilder sb = new StringBuilder();
                while ((line = reader.readLine()) != null)
                {
                    sb.append(line + "\n");
                }
                // Response from server after login process will be stored in response variable.                
                response = sb.toString();
                // You can perform UI operations here
                Toast.makeText(this,"Message from Server: \n"+ response, 0).show();             
                isr.close();
                reader.close();

            }
            catch(IOException e)
            {
                // Error
            }
    }
}

PHP File That Receives username and password and I need this file to also send database Columns values for the username and password PHP文件接收用户名和密码,我需要此文件也发送用户名和密码的数据库列值

<?php   
$host="localhost"; // Host name 
$user="test"; // Mysql username 
$pswd="123"; // Mysql password 
$db="pet_home"; // Database name 
//$tbl_name="users"; // Table name

$conn = mysql_connect($host, $user, $pswd);
mysql_select_db($db, $conn);
$username=$_POST['username'];
$password=$_POST['password'];
$result=mysql_query("select * from users where username='$username' and password='$password'")or die (mysql_error());
$count=mysql_num_rows($result);
$row=mysql_fetch_array($result);    
        if ($count > 0){
        echo 1;     
        }else{
        echo 0;
        }
?>

The values you want will be in the $row array. 您想要的值将在$ row数组中。 You can access them (depending on the column you want) like this $row[0], $row[1], etc. 您可以访问它们(取决于您想要的列),例如$ row [0],$ row [1]等。

It looks like the response currently is just the echo'd value 0 or 1 看起来响应当前只是echo'd值0或1

Why not just append them to that string separated by an uncommon character like the pipe or asterisk then split it back up? 为什么不将它们附加到由不常见的字符(如管道或星号)分隔的字符串,然后将其拆分回来?

Your echo then would be something like 那么你的回声就像是

echo 1."|".$row[0]."|".$row[1];

etc. 等等

** Also, I should add the obigitory "hash your passwords and consider security" **此外,我应该添加obigitory“哈希密码并考虑安全性”

try this 尝试这个

 try{
                     HttpClient httpclient = new DefaultHttpClient();
                     HttpPost httppost = new HttpPost(url);
                     httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                     HttpResponse response = httpclient.execute(httppost);
                     String the_string_response = convertResponseToString(response);
                     Toast.makeText(getApplicationContext(), "Response " + the_string_response, Toast.LENGTH_LONG).show();
                 }catch(Exception e){
                       Toast.makeText(getApplicationContext(), "ERROR " + e.getMessage(), Toast.LENGTH_LONG).show();
                      System.out.println("Error in http connection "+e.toString());
                 }

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

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