从HTTP POST请求的Andr​​oid空响应 [英] Null response from HTTP Post Request Android

查看:155
本文介绍了从HTTP POST请求的Andr​​oid空响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图建立到服务器的请求来PHP脚本,将检查,看是否有用户在数据库中存在。目前,我只是想确认我收到一些回应。我试图输出 responseString 当用户presses登录按钮,但每次回来的时间。有谁知道为什么?

这是我的 MainActivity

 公共类MainActivity延伸活动{的EditText用户名;
的EditText密码;
按钮loginBtn;
的LinearLayout登录表单;
串passwordDetail;
串usernameDetail;
字符串URL =htt​​p://www.mysite.com/example/checklogin.php; 字符串responseString = NULL;@覆盖
保护无效的onCreate(捆绑savedInstanceState){
    super.onCreate(savedInstanceState);
    的setContentView(R.layout.activity_main);    //隐藏操作栏
    动作条AB;
    AB = this.getActionBar();
    ab.hide();    //获取XML引用
    用户名=(的EditText)findViewById(R.id.username);
    密码=(EditText上)findViewById(R.id.password);
    loginBtn =(按钮)findViewById(R.id.loginBtn);
    登录表单=(的LinearLayout)findViewById(R.id.loginform);    //动画
    最后AlphaAnimation淡入=新AlphaAnimation(0.0,1.0F);
    AlphaAnimation淡出=新AlphaAnimation(1.0F,0.0);
    fadeIn.setDuration(1200);
    fadeIn.setFillAfter(真);
    fadeOut.setDuration(1200);
    fadeOut.setFillAfter(真);
    fadeOut.setStartOffset(4200+ fadeIn.getStartOffset());    //线程运行2秒后启动动画
    处理程序处理程序=新的处理程序();
    handler.postDelayed(新的Runnable(){        公共无效的run(){
            //显示登录表单
            loginform.startAnimation(淡入);
            loginBtn.setOnClickListener(新View.OnClickListener(){
                公共无效的onClick(视图v){
                    //显示();
                    Toast.makeText(getApplicationContext(),检查登录详细信息...,Toast.LENGTH_SHORT).show();
                    如果(checkLoginDetails()){
                        //打开了新的活力
                        //关闭闪屏
                        //完();
                        //启动主屏幕
                        意向意图=新意图(v.getContext(),SectionsActivity.class);
                        // startActivity(意向);
                        //创建两个活动之间的动画褪色
                        overridePendingTransition(R.anim.fade_in,R.anim.splash_fade_out);
                        Toast.makeText(getApplicationContext()登录成功+ responseString,Toast.LENGTH_SHORT).show();                    }
                    其他{
                        Toast.makeText(getApplicationContext(),登录失败,Toast.LENGTH_SHORT).show();                    }
                }
            });        }    },2000);
}//继续之前,请检查登录详细信息。
公共布尔checkLoginDetails(){
    。usernameDetail = username.getText()的toString();
    。passwordDetail = password.getText()的toString();
    新RequestTask()执行(URL,usernameDetail,passwordDetail);
    返回true;
}

这是PHP脚本,我要求 - 在那一刻我已经很难codeD细节我知道数据库存在,只是想专注于获得回说用户存在的响应。

 < PHP
mysql_connect(xxx.xxx.xxx.xxx,用户名,密码)或死亡(无法选择数据库。);
mysql_select_db(数据库名称)或死亡(无法选择数据库。);// $用户名= $ _ POST [用户名];
// $密码= $ _ POST ['密码'];$ pwdMD5 = MD5(123);$ SQL =SELECT * FROM成员其中username ='用户1'和密码= $ pwdMD5';
$结果= mysql_query($的SQL)或死亡(mysql_error());
$其行= mysql_num_rows($结果);
如果($ numRows行大于0)
   {
    回声用户出现;
    返回true;
   }
其他
   {
    回声用户未找到';
    返回false;}
   ?>

这是我的的AsyncTask

 类RequestTask扩展的AsyncTask<字符串,字符串,字符串> {    @覆盖
    保护字符串doInBackground(字符串... URI){
        HttpClient的HttpClient的=新DefaultHttpClient();
        HTT presponse响应;
        responseString = NULL;
        尝试{
            响应= httpclient.execute(新HttpPost(URI [0]));
            状态行状态行= response.getStatusLine();
            如果(statusLine.getStatus code()== HttpStatus.SC_OK){
                ByteArrayOutputStream出=新ByteArrayOutputStream();
                。response.getEntity()的writeTo(出);
                out.close();
                responseString = out.toString();
            }其他{
                //关闭连接。
                。response.getEntity()的getContent()close()方法。
                抛出新IOException异常(statusLine.getReasonPhrase());
            }
        }赶上(ClientProtocolException E){
            // TODO处理问题..
        }赶上(IOException异常五){
            // TODO处理问题..
        }
        返回responseString;
    }


解决方案

由于在执行code异步为null。你敬酒结果,而HTTP请求尚未完成执行你的PHP脚本。

尝试把你举杯 onPostExecute(字符串结果)方式在你的AsyncTask类。

  @覆盖
    保护无效onPostExecute(字符串结果){
        super.onPostExecute(结果);
        //吐司结果。
    }

I am trying to make a request to a server to a php script which will check to see if a user exists in a database. Currently I just want to make sure I am receiving some sort of response. I try to output the value of responseString when the user presses the login button but every time it comes back as null. Does anyone know why??

This is my MainActivity

public class MainActivity extends Activity {

EditText username;
EditText password;
Button loginBtn;
LinearLayout loginform;
String passwordDetail;
String usernameDetail;
String url = "http://www.mysite.com/example/checklogin.php";

 String responseString = null;

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

    //Hide the Action Bar
    ActionBar ab;
    ab = this.getActionBar();
    ab.hide();

    //Get references to XML
    username = (EditText)findViewById(R.id.username);
    password = (EditText)findViewById(R.id.password);
    loginBtn = (Button)findViewById(R.id.loginBtn);
    loginform = (LinearLayout)findViewById(R.id.loginform);

    //Animation
    final AlphaAnimation fadeIn = new AlphaAnimation(0.0f , 1.0f ); 
    AlphaAnimation fadeOut = new AlphaAnimation( 1.0f , 0.0f ) ; 
    fadeIn.setDuration(1200);
    fadeIn.setFillAfter(true);
    fadeOut.setDuration(1200);
    fadeOut.setFillAfter(true);
    fadeOut.setStartOffset(4200+fadeIn.getStartOffset());

    //Run thread after 2 seconds to start Animation
    Handler handler = new Handler();
    handler.postDelayed(new Runnable(){

        public void run() {
            //display login form
            loginform.startAnimation(fadeIn);
            loginBtn.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    //display();
                    Toast.makeText(getApplicationContext(), "Checking login details...", Toast.LENGTH_SHORT).show();
                    if(checkLoginDetails()){
                        //OPENS NEW ACTIVITY
                        //Close splash screen
                        //finish();
                        //start home screen 
                        Intent intent = new Intent(v.getContext(), SectionsActivity.class);
                        //startActivity(intent);
                        //creates fade in animation between two activities
                        overridePendingTransition(R.anim.fade_in, R.anim.splash_fade_out);
                        Toast.makeText(getApplicationContext(), "Login Successful" + responseString, Toast.LENGTH_SHORT).show();

                    }
                    else{
                        Toast.makeText(getApplicationContext(), "Login Unsuccessful", Toast.LENGTH_SHORT).show();

                    }
                }
            });

        }

    }, 2000);
}

//Check the login details before proceeding.
public boolean checkLoginDetails(){
    usernameDetail = username.getText().toString();
    passwordDetail = password.getText().toString();
    new RequestTask().execute(url, usernameDetail, passwordDetail);
    return true;
}

This is the php script I'm requesting - At moment I've hard coded details I know to exist in db and just want to focus on getting back a response to say user exists.

    <?php
mysql_connect("xxx.xxx.xxx.xxx", "username", "password") or die("Couldn't select database.");
mysql_select_db("databasename") or die("Couldn't select database.");

//$username = $_POST['username'];
//$password = $_POST['password'];

$pwdMD5 = md5(123);

$sql = "SELECT * FROM membership WHERE Username = 'user1' AND Password = '$pwdMD5' ";
$result = mysql_query($sql) or die(mysql_error());
$numrows = mysql_num_rows($result);
if($numrows > 0)
   {
    echo 'user found';
    return true;
   }
else
   {
    echo 'user not found';
    return false;

}
   ?>

This is my AsyncTask.

 class RequestTask extends AsyncTask<String, String, String>{

    @Override
    protected String doInBackground(String... uri) {
        HttpClient httpclient = new DefaultHttpClient();
        HttpResponse response;
        responseString = null;
        try {
            response = httpclient.execute(new HttpPost(uri[0]));
            StatusLine statusLine = response.getStatusLine();
            if(statusLine.getStatusCode() == HttpStatus.SC_OK){
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                response.getEntity().writeTo(out);
                out.close();
                responseString = out.toString();
            } else{
                //Closes the connection.
                response.getEntity().getContent().close();
                throw new IOException(statusLine.getReasonPhrase());
            }
        } catch (ClientProtocolException e) {
            //TODO Handle problems..
        } catch (IOException e) {
            //TODO Handle problems..
        }
        return responseString;
    }

解决方案

It is null because you execute the code asynchronously. You Toast the result while the HTTP request is not yet finished executing your PHP script.

Try putting your Toast to onPostExecute(String result) method in your AsyncTask class.

@Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        //Toast result. 
    }

这篇关于从HTTP POST请求的Andr​​oid空响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆