php - 无 HTTP 响应的 HTTP 请求

标签 php android mysql httprequest httpresponse

我只需要知道我的申请中缺少什么 我的 Android 应用程序以 HTTP POST 形式发送用户名和密码,然后 PHP 文件使用数据库中该用户名的值进行响应 问题是当我输入用户名和密码时,Toast 中没有任何返回,甚至没有显示

主要 Activity

package com.example.postapp;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.ArrayList;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;



import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
      TextView tv;
      EditText u,p;
      Button login;
      String result;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        login = (Button) findViewById(R.id.login);

        login.setOnClickListener(new OnClickListener(){

            @Override
            public void onClick(View v) {

                u = (EditText) findViewById(R.id.username);
                p = (EditText) findViewById(R.id.password);


                Toast.makeText(getApplicationContext(), u.getText().toString(), Toast.LENGTH_LONG).show();
                Toast.makeText(getApplicationContext(), p.getText().toString(), Toast.LENGTH_LONG).show();
                new MyAsyncTask().execute(u.getText().toString(),p.getText().toString());

            }

        });


    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
    public class MyAsyncTask extends AsyncTask<String, Integer, Boolean>{
        String host;


        @Override
        protected Boolean doInBackground(String... params) {
            // TODO Auto-generated method stub
            Boolean a= postData(params[0],params[1]);       
            return a;
        } 

        protected void onPostExecute(Boolean localres){
            tv = (TextView) findViewById(R.id.tv);
             if (localres){
                    tv.setText("A Correct Username and Password");
                }else{
                    tv.setText("Incorrect Username or Password");
                }
            // Toast.makeText(getApplicationContext(), result.toString(), Toast.LENGTH_SHORT).show();
            //    Toast.makeText(getApplicationContext(), "command sent", Toast.LENGTH_SHORT).show();
                if(host!=null)
                {
              //  Toast.makeText(getApplicationContext(), host.toString(), Toast.LENGTH_LONG).show();
                }
        }

        protected void onProgressUpdate(Integer... progress){
            //pb.setProgress(progress[0]);
            //Toast.makeText(getApplicationContext(), "Done", Toast.LENGTH_LONG).show();

        }


        public Boolean postData(String a,String b) {
             // ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
            //  postParameters.add(new BasicNameValuePair("username", a));
             // postParameters.add(new BasicNameValuePair("password", b));
              HttpURLConnection connection;
              OutputStreamWriter request = null;

                   URL url = null;   
                   String response = null;         
                   String parameters = "username="+a+"&password="+b;   

                   try
                   {
                       url = new URL("http://"+"192.168.1.3"+"/new/check2.php");
                       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(getApplicationContext(),"Message from Server: \n"+ response, 0).show();             
                       isr.close();
                       reader.close();

                   }
                   catch(Exception e)
                   {
                       e.printStackTrace();
                   }
                   return true;
           }


        }



    }

PHP

<?php

$con = mysqli_connect("localhost", "root", "123", "pet_home");
if (mysqli_connect_errno()) {
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$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 $row['filter_st'];
    echo "<br>";
    echo $row['heat_st'];
    echo "<br>";
    echo $row['led_st'];
} else {
    echo 0;
}

mysqli_close($con);

Logcat出现异常

12-13 20:57:45.534: W/System.err(14768): java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
12-13 20:57:45.534: W/System.err(14768):    at android.os.Handler.<init>(Handler.java:197)
12-13 20:57:45.534: W/System.err(14768):    at android.os.Handler.<init>(Handler.java:111)
12-13 20:57:45.538: W/System.err(14768):    at android.widget.Toast$TN.<init>(Toast.java:324)
12-13 20:57:45.538: W/System.err(14768):    at android.widget.Toast.<init>(Toast.java:91)
12-13 20:57:45.538: W/System.err(14768):    at android.widget.Toast.makeText(Toast.java:238)
12-13 20:57:45.538: W/System.err(14768):    at com.example.postapp.MainActivity$MyAsyncTask.postData(MainActivity.java:136)
12-13 20:57:45.538: W/System.err(14768):    at com.example.postapp.MainActivity$MyAsyncTask.doInBackground(MainActivity.java:76)
12-13 20:57:45.538: W/System.err(14768):    at com.example.postapp.MainActivity$MyAsyncTask.doInBackground(MainActivity.java:1)
12-13 20:57:45.538: W/System.err(14768):    at android.os.AsyncTask$2.call(AsyncTask.java:287)
12-13 20:57:45.538: W/System.err(14768):    at java.util.concurrent.FutureTask.run(FutureTask.java:234)
12-13 20:57:45.538: W/System.err(14768):    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
12-13 20:57:45.538: W/System.err(14768):    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
12-13 20:57:45.538: W/System.err(14768):    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
12-13 20:57:45.538: W/System.err(14768):    at java.lang.Thread.run(Thread.java:841)

最佳答案

Toast.makeText(getApplicationContext(),"Message from Server: \n"+ response, 0).show();          

你有

Boolean a= postData(params[0],params[1]); // in doInbackground

public Boolean postData(String a,String b) 中,您显示的 toast 是错误的

您正在后台线程中更新用户界面,这是不可能的。在 ui 线程上更新 ui。

doInbackground中返回结果。 doInbackground 计算的结果是 onPostExecute 的参数。因此,根据结果,您可以相应地更新 ui ie 显示 toast。

或使用runOnUiThread

runOnUiThread(new Runnable(){
    public void run() {
         Toast.makeText(getApplicationContext(),"Message from Server: \n"+ response, 0).show(); 
    }
 });

关于php - 无 HTTP 响应的 HTTP 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20575973/

相关文章:

php - 在 Selenium Chrome 中将语言设置为 en-UK 以进行 Behat 测试

android - andEngine 中的可变文本更新速度变慢

android - 如何像谷歌地图应用程序一样将谷歌标志移动到透明操作栏上方?安卓

java - 如何使用java从外部服务器检查tomcat/mysql

sql - 如何检查至少一行符合 MySQL 中的条件(WHERE 子句)?

php - LIKE 运算符中的多个条件

php - 单击重定向到不同页面的提交按钮时如何打开 Bootstrap 模式?

php - 如何正确解释哈希方案的递归伪代码

php - 将字符串存储在 php 的变量中并在 mysql 数据库中搜索该变量?

android - 应用程序在安装时不要求互联网许可