发布数据从Android到PHP文件返回空字符串

时间:2017-04-18 13:11:09

标签: java php android string

我已就此主题研究了大量材料。我跟随他们的例子都没有用。

我将数据(txtUsername和txtPassword)从Android应用程序发布到php文件。

此代码中的问题,HTTPConnection 发布空字符串到php文件。 我使用过Uri String builder,以及其他构建字符串的方法......它们都返回" Empty Strings Parsed"。

主要活动代码

*

package com.example.examinationportal;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.graphics.Color;
import android.net.Uri;
import android.os.AsyncTask;
import android.provider.Settings;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.app.IntentService;
import android.app.PendingIntent;
import org.apache.http.NameValuePair;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.io.InputStream;
public class MainActivity extends AppCompatActivity {
    public String message = "";
    SQLiteDatabase myDB = null;
    public String TableName = "Users";
    public String Data;
    public String responseData;
    public String username;
    public  String password;
    public String data;
    public String query;
    TextView statusBar, titleLogin;
    EditText un, pw;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // Get user defined values
        un = (EditText) findViewById(R.id.editTextUsername);//username field
        pw = (EditText) findViewById(R.id.editTextPassword);//password field
        username = un.getText().toString();//convert username and password to string and parse
        password = pw.getText().toString();//them to variables
        //initialize the status bar textview control
        statusBar = (TextView) findViewById(R.id.textViewStatusMsg);
        titleLogin = (TextView) findViewById(R.id.textViewLogin);//title text of this UI
    }

//创建GetText方法

    private   class  GetText  extends AsyncTask<Void, Void, Void> {//} throws UnsupportedEncodingException {
        @Override
        protected Void doInBackground(Void...params){
            BufferedReader reader = null;
            // Send data
            try {
                // Defined URL  where to send data
                URL url = new URL("http://www.naomiedify.com/school/test/login2.php");
                //URLConnection con = url.openConnection();
                HttpURLConnection con = (HttpURLConnection) url.openConnection();
                con.setRequestProperty("Accept-Charset", "UTF-8");
                con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                con.setRequestMethod("POST");
                con.setReadTimeout(10000);
                con.setConnectTimeout(15000);

//这是要发送到php服务器的数据 //请注意,我使用不同的方法构建字符串以发送到服务器,但字符串在发布之前会被修剪。我无法使用 NameValuePair ,因为它在Android 2.3中已弃用 例如: 方法1:

//this method returns empty strings
                query = URLEncoder.encode("txtUserName" +username,"UTF-8");
                query += URLEncoder.encode("&txtPassword" +password, "UTF-8");
                query += URLEncoder.encode("&cmbType=Aptitude Test", "UTF-8");

方法2:

//this method also returns empty strings
Uri.Builder builder = new Uri.Builder()
                        .appendQueryParameter("txtUserName", username)
                        .appendQueryParameter("txtPassword", password)
                        .appendQueryParameter("cmbType", "Aptitude Test");
                query = builder.build().getEncodedQuery();

//发送POST数据请求

                con.setDoOutput(true);
                OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream());

                wr.write( query );
                wr.flush();
                wr.close();

//获取服务器响应

                reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
                StringBuilder sb = new StringBuilder();
                String line;

//读取服务器响应

                while((line = reader.readLine()) != null) {

//在字符串

中附加服务器响应
                    sb.append(line + "\n");
                    Log.d("Response: ", "> " + line);
                }
                reader.close();
                responseData = sb.toString();
            }
            catch (MalformedURLException e) {
                e.printStackTrace();
                responseData = e.toString();
            }
            catch (IOException e) {
                e.printStackTrace();
                responseData = e.toString();
            }
            return null;
        }

//启动onPostExecute事件

        @Override
        protected void onPostExecute(Void result){
            statusBar.setText(responseData);
            super.onPostExecute(result);
        }
    }

// onClick事件的登录代码

    public void loginUser(View login) {// Called when the user taps the login button
        Intent intent = new Intent(this, DisplayWelcomeScreen.class);//start the ui

//从php服务器获取响应

        new GetText().execute();
        try{
            //check the login using the post back data
            if (responseData.equals("User Found.")) {
                message = "Welcome"; //message for successful login
                // Show respsonse on activity
                statusBar.setText( responseData  );
                Bundle bundle = new Bundle();//bundle the message and parse it to the next activity
                bundle.putString("dispMsg", message);//bundle the message using the variable dispMsg
                intent.putExtras(bundle);
                startActivity(intent);
            } else {
                message = "Incorrect Username or Password. Try again!";
                statusBar.setTextColor(Color.parseColor("#ff0000"));
                statusBar.setBackgroundColor(Color.parseColor("#d3d3d3"));
                // Show response on activity
                statusBar.setText( responseData  + ": Incorrect Username or Password.");
            }
        }
        catch(Exception ex) {
            statusBar.setText("URL Exeption! "+ex);
        }
    }
}

PHP代码[login2.php]

<?php
$dataComingFrom = substr($_SERVER['HTTP_USER_AGENT'], 0, 7);
//echo $dataComingFrom;

    $con = mysqli_connect($hostname_school,$username_school,"$password_school");//connect to server
    mysqli_select_db($con,$_db);
    if (mysqli_connect_errno()){//if error connecting to server, return error message
        die("Failed to connect to MySQL: " . mysqli_connect_error());

    }else if(!mysqli_select_db($con,$_db)) {//if no error connecting to server, try to select db to see whether it already exists. 

        if ($perform = mysqli_query($con,"CREATE DATABASE IF NOT EXISTS $_db")){ //if no db exists on the server, create the db. 
            $msg = "Database $_db has been created successfully"; 
            //echo $msg;
        }else { echo mysqli_errno($con) .": Error creating database: " . mysqli_error($con);}//if it can't create db, return error message

    }else{ //if db was selected, it means the db already exists 
        //$data = "You have already created this database!";//return message that db already exists 
        //die("$data <br>");//kill the script

        //you can perform the login process here
        //$ip           = preg_replace( '#[^0-9.]#', '', getenv( 'REMOTE_ADDR' ) );
        $username = stripslashes( str_replace( "[^A-Z a-z0-9]", "", $_POST[ 'txtUserName' ] ) );
        $plainPass = stripslashes( str_replace( "[^A-Z a-z0-9]", "", $_POST[ 'txtPassword' ] ) );
        $password   = strrev(md5($plainPass));

        //run the query to search for the username and password for a match
        //$query = "SELECT * FROM $tbl_name WHERE first_name = '$un' AND password = '$pw'";

        if(empty($username) or empty($plainPass)){die("Empty Strings Parsed.");}

    $user = mysqli_query($con,"SELECT * FROM ap_student WHERE AS_Email ='".$username."' AND AS_Password ='".$password."' AND 
    AS_Status ='Confirmed!'") or die("Unable to verify user due to: " . mysqli_error($con));

    //$insert = mysqli_query($con,"UPDATE ap_student SET AS_Password = '".$password."' WHERE AS_Id = 1") or die(mysqli_error($con));

    $result = mysqli_num_rows($user);
    if ($result > 0){$returnedString = "User Found.";}else {$returnedString = "User Not Found";echo $returnedString;}

}
?>

** ANDROIDMANIFEST.XML **

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.examinationportal">

    <uses-permission
        android:name="android.permission.INTERNET">
    </uses-permission>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.AppCompat.DayNight.DarkActionBar">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
     </application>
</manifest>

* 请帮帮我...我不知道我哪里出错了。 提示:我是Android编程的新手。

谢谢。

这是最新的代码....尽管如此,PHP仍然会返回&#34;空字符串解析&#34;。

package com.example.examinationportal;

import statements here...
public class MainActivity extends AppCompatActivity {
    public String message = "";

    SQLiteDatabase myDB = null;
    public String TableName = "Users";
    public String Data = "";
    public String responseData = "";
    public String username = "";
    public  String password = "";
    public String data = "";

    TextView statusBar, titleLogin;
    EditText un, pw;

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

        // Get user defined values
        un = (EditText) findViewById(R.id.editTextUsername);//username field
        pw = (EditText) findViewById(R.id.editTextPassword);//password field
        username = un.getText().toString();//convert username and password to string and parse
        password = pw.getText().toString();//them to variables

        //initialize the status bar textview control
        statusBar = (TextView) findViewById(R.id.textViewStatusMsg);

        titleLogin = (TextView) findViewById(R.id.textViewLogin);//title text of this UI
    }

    public void loginUser(View login) {// Called when the user taps the login button
        Intent intent = new Intent(this, DisplayWelcomeScreen.class);//start the ui
        new GetText().execute();

        try{
            //check the login using the post back data
            if (responseData.equals("User Found.")) {
                message = "Welcome"; //message for successful login
                // Show respsonse on activity
                statusBar.setText( responseData  );
                Bundle bundle = new Bundle();//bundle the message and parse it to the next activity
                bundle.putString("dispMsg", message);//bundle the message using the variable dispMsg
                intent.putExtras(bundle);
                startActivity(intent);
            } else {
                message = "Incorrect Username or Password. Try again!";
                statusBar.setTextColor(Color.parseColor("#ff0000"));
                statusBar.setBackgroundColor(Color.parseColor("#d3d3d3"));
                // Show response on activity
                statusBar.setText( responseData  + ": Incorrect Username or Password.");
            }
        }
        catch(Exception ex) {
            statusBar.setText("URL Exeption! "+ex);
        }
    }

    // Create GetText Method
    public class  GetText  extends AsyncTask<Void, Void, Void> {//} throws UnsupportedEncodingException {

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

            BufferedReader reader = null;

            // Send data
            try {
                // Defined URL  where to send data
                URL url = new URL("http://www.naomiedify.com/school/test/login2.php");
                //URLConnection con = url.openConnection();
                HttpURLConnection con = (HttpURLConnection) url.openConnection();

                con.setRequestProperty("Accept-Charset", "UTF-8");
                con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
                con.setRequestMethod("POST");
                con.setReadTimeout(10000);
                con.setConnectTimeout(15000);

           /*     data = URLEncoder.encode("txtUserName", "UTF-8") +"=" +URLEncoder.encode(username,"UTF-8")
                        +"&" +URLEncoder.encode("txtPassword", "UTF-8") +"=" +URLEncoder.encode(password, "UTF-8")
                +"&" +URLEncoder.encode("cmbType", "UTF-8") +"=" +URLEncoder.encode("Aptitude Test", "UTF-8");*/
                Uri.Builder builder = new Uri.Builder()
                        .appendQueryParameter("txtUserName", username)
                        .appendQueryParameter("txtPassword", password)
                        .appendQueryParameter("cmbType", "Aptitude Test");
                String query = builder.build().getEncodedQuery();

                // Send POST data request
                con.setDoOutput(true);
                OutputStream os = con.getOutputStream();
                //OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream());
                BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));

                wr.write( query );
                wr.flush();
                wr.close();
                os.close();

                //con.connect();

                // Get the server response
                reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
                StringBuilder sb = new StringBuilder();
                String line;

                // Read Server Response
                while((line = reader.readLine()) != null) {
                    // Append server response in string
                    sb.append(line + "\n");
                    Log.d("Response: ", "> " + line);
                }
                reader.close();
                responseData = sb.toString();
            }
            catch (MalformedURLException e) {
                e.printStackTrace();
                responseData = e.toString();
                // new URL() failed
            }
            catch (IOException e) {
                e.printStackTrace();
                responseData = e.toString();
                // openConnection() failed
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result){
            statusBar.setText(responseData);
            super.onPostExecute(result);
        }
    }
}

我已经重新编辑了整个代码......下面...... 结果仍然是#34;空字符串&#34;发布到PHP。

package com.example.examinationportal;

import statements here...
public class MainActivity extends AppCompatActivity {
    public String message = "";

    SQLiteDatabase myDB = null;
    public String TableName = "Users";
    public String Data = "";
    public String responseData = "";
    public String username = "";
    public  String password = "";
    public String data = "";

    TextView statusBar, titleLogin;
    EditText un, pw;

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

        // Get user defined values
        un = (EditText) findViewById(R.id.editTextUsername);//username field
        pw = (EditText) findViewById(R.id.editTextPassword);//password field
        username = un.getText().toString();//convert username and password to string and parse
        password = pw.getText().toString();//them to variables

        //initialize the status bar textview control
        statusBar = (TextView) findViewById(R.id.textViewStatusMsg);

        titleLogin = (TextView) findViewById(R.id.textViewLogin);//title text of this UI
    }
    // Create GetText Method
    public class  GetText  extends AsyncTask<Void, Void, Void> {//} throws UnsupportedEncodingException {

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

            BufferedReader reader = null;

            // Send data
            try {
                // Defined URL  where to send data
                URL url = new URL("http://www.naomiedify.com/school/test/login2.php");
                //URLConnection con = url.openConnection();
                HttpURLConnection con = (HttpURLConnection) url.openConnection();

                con.setRequestProperty("Accept-Charset", "UTF-8");
                con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
                con.setRequestMethod("POST");
                con.setReadTimeout(10000);
                con.setConnectTimeout(15000);

           /*     data = URLEncoder.encode("txtUserName", "UTF-8") +"=" +URLEncoder.encode(username,"UTF-8")
                        +"&" +URLEncoder.encode("txtPassword", "UTF-8") +"=" +URLEncoder.encode(password, "UTF-8")
                +"&" +URLEncoder.encode("cmbType", "UTF-8") +"=" +URLEncoder.encode("Aptitude Test", "UTF-8");*/
                Uri.Builder builder = new Uri.Builder()
                        .appendQueryParameter("txtUserName", username)
                        .appendQueryParameter("txtPassword", password)
                        .appendQueryParameter("cmbType", "Aptitude Test");
                String query = builder.build().getEncodedQuery();

                // Send POST data request
                con.setDoOutput(true);
                OutputStream os = con.getOutputStream();
                //OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream());
                BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));

                wr.write( query );
                wr.flush();
                wr.close();
                os.close();

                //con.connect();

                // Get the server response
                reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
                StringBuilder sb = new StringBuilder();
                String line;

                // Read Server Response
                while((line = reader.readLine()) != null) {
                    // Append server response in string
                    sb.append(line + "\n");
                    Log.d("Response: ", "> " + line);
                }
                reader.close();
                responseData = sb.toString();
            }
/*            catch (MalformedURLException e) {
                e.printStackTrace();
                responseData = e.toString();
                // new URL() failed
            }*/
            catch (IOException e) {
                e.printStackTrace();
                responseData = e.toString();
                // openConnection() failed
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result){
            statusBar.setText(responseData);
            super.onPostExecute(result);

            try{
                //check the login using the post back data
                if (responseData.equals("User Found.")) {
                    message = "Welcome"; //message for successful login
                    // Show respsonse on activity
                    statusBar.setText( message  );
                } else {
                    message = "Incorrect Username or Password. Try again!";
                    statusBar.setTextColor(Color.parseColor("#ff0000"));
                    statusBar.setBackgroundColor(Color.parseColor("#d3d3d3"));
                    // Show response on activity
                    statusBar.setText("Incorrect Username or Password.");
                }
            }
            catch(Exception ex) {
                statusBar.setText("URL Exeption! "+ex);
            }
        }
    }

    public void loginUser(View login) {// Called when the user taps the login button
        new GetText().execute();

        /*Intent intent = new Intent(this, DisplayWelcomeScreen.class);//start the ui
        Bundle bundle = new Bundle();//bundle the message and parse it to the next activity
        bundle.putString("dispMsg", message);//bundle the message using the variable dispMsg
        intent.putExtras(bundle);
        startActivity(intent);*/
    }
}

亲爱的朋友, 正如你们所建议的,我已经解决了我的应用程序代码... 该应用程序能够将数据发布到php服务器并接收数据。

但是我无法评估数据以便StartActivity(intent)。 请在下面输入以下代码......

import statemen;
public class MainActivity extends AppCompatActivity {
    public String message = "";
    public String Data = "";
    public String responseData = "";
    public String username = "";
    public  String password = "";
    public String data = "";
    Intent intent;

    TextView statusBar, titleLogin;
    EditText un, pw;

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

        //initialize the status bar textview control
        statusBar = (TextView) findViewById(R.id.textViewStatusMsg);
        titleLogin = (TextView) findViewById(R.id.textViewLogin);//title text of this UI
    }

    public void newUser(View register) {
        Intent i = new Intent(this, RegisterUserActivity.class);//start the ui for new user
        startActivity(i);
    }

    public void loginUser(View login) {// Called when the user taps the login button
        intent = new Intent(this, DisplayWelcomeScreen.class);//start the ui

        // Get user defined values
        un = (EditText) findViewById(R.id.editTextUsername);//username field
        pw = (EditText) findViewById(R.id.editTextPassword);//password field
        username = un.getText().toString();//convert username and password to string and parse
        password = pw.getText().toString();//them to variables

        new GetText().execute();
    }

    // Create GetText Method
    public class  GetText  extends AsyncTask<Void, Void, Void> {//} throws UnsupportedEncodingException {

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

            BufferedReader reader = null;

            // Send data
            try {
                // Defined URL  where to send data
                URL url = new URL("http://www.naomiedify.com/school/test/login2.php");
                //URLConnection con = url.openConnection();
                HttpURLConnection con = (HttpURLConnection) url.openConnection();

                con.setRequestProperty("Accept-Charset", "UTF-8");
                con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
                con.setRequestMethod("POST");
                con.setReadTimeout(10000);
                con.setConnectTimeout(15000);

                Uri.Builder builder = new Uri.Builder()
                        .appendQueryParameter("txtUserName", username)
                        .appendQueryParameter("txtPassword", password)
                        .appendQueryParameter("cmbType", "Aptitude Test");
                String query = builder.build().getEncodedQuery();

                // Send POST data request
                con.setDoOutput(true);
                OutputStream os = con.getOutputStream();
                //OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream());
                BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));

                wr.write( query );
                wr.flush();
                wr.close();
                os.close();

                // Get the server response
                reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
                StringBuilder sb = new StringBuilder();
                String line;

                // Read Server Response
                while((line = reader.readLine()) != null) {
                    // Append server response in string
                    sb.append(line + "\n");
                    //Log.d("", "" + line);
                }
                reader.close();
                responseData = sb.toString();
                Log.d("Server Data", ":"+responseData);
                Data = responseData;
            }
            catch (IOException e) {
                e.printStackTrace();
                responseData = e.toString();
            }
            return null;


}

        @Override
        protected void onPostExecute(Void result){
            super.onPostExecute(result);

//此时,Data计算为not null

statusBar.setText(Data);

//检查从发布的返回数据返回的Data变量,然后将用户登录到下一个活动。

if (Data.equals("User Found.")) {

///但此时,Data为null,而else {}块将被评估。

 message = "Welcome"; 
                statusBar.setText( message  );
                Bundle bundle = new Bundle();
                bundle.putString("dispMsg", message); 
                intent.putExtras(bundle);
                startActivity(intent);
            } else {
                message = "Incorrect Username or Password. Try again!";
                statusBar.setText(message);
            }
        }
    }
}

2 个答案:

答案 0 :(得分:0)

 new GetText().execute();

将该语句之后的所有代码放在onPostExecute中。现在,您在异步任务开始发布之前执行该代码。

username = un.getText().toString();//convert username and password to string and parse
password = pw.getText().toString();//them to variables

onCreate()太早了。将这些行移到loginUser()。

答案 1 :(得分:0)

我非常感谢您的贡献和您的痛苦支持。 我找到了解决问题的方法。

以下是文档的完整代码。

package com.example.examinationportal;

import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.graphics.Color;
import android.net.Uri;
import android.os.AsyncTask;
import android.provider.Settings;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.app.IntentService;
import android.app.PendingIntent;

import org.apache.http.NameValuePair;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.io.InputStream;
public class MainActivity extends AppCompatActivity {
    public String message = "";
    public String Data = "";
    public String responseData = "";
    public String username = "";
    public  String password = "";
    public String data = "";
    public Intent intent;
    public StringBuilder sb;
    public String line;
    TextView statusBar, titleLogin;
    EditText un, pw;

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

        //initialize the status bar textview control
        statusBar = (TextView) findViewById(R.id.textViewStatusMsg);
        titleLogin = (TextView) findViewById(R.id.textViewLogin);//title text of this UI
    }

    public void newUser(View register) {
        Intent i = new Intent(this, RegisterUserActivity.class);//start the ui for new user
        startActivity(i);
    }

    public void loginUser(View login) {// Called when the user taps the login button
        intent = new Intent(this, DisplayWelcomeScreen.class);//start the ui

        // Get user defined values
        un = (EditText) findViewById(R.id.editTextUsername);//username field
        pw = (EditText) findViewById(R.id.editTextPassword);//password field
        username = un.getText().toString();//convert username and password to string and parse
        password = pw.getText().toString();//them to variables

        new GetText().execute();
    }

    // Create GetText Method
    public class  GetText  extends AsyncTask<Void, Void, Void> {//} throws UnsupportedEncodingException {

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

            BufferedReader reader = null;

            // Send data
            try {
                // Defined URL  where to send data
                URL url = new URL("http://www.naomiedify.com/school/test/login2.php");
                //URLConnection con = url.openConnection();
                HttpURLConnection con = (HttpURLConnection) url.openConnection();

                con.setRequestProperty("Accept-Charset", "UTF-8");
                con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
                con.setRequestMethod("POST");
                con.setReadTimeout(10000);
                con.setConnectTimeout(15000);

                Uri.Builder builder = new Uri.Builder()
                        .appendQueryParameter("txtUserName", username)
                        .appendQueryParameter("txtPassword", password)
                        .appendQueryParameter("cmbType", "Aptitude Test");
                String query = builder.build().getEncodedQuery();

                // Send POST data request
                con.setDoOutput(true);
                OutputStream os = con.getOutputStream();
                //OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream());
                BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));

                wr.write(query);
                wr.flush();
                wr.close();
                os.close();

                // Get the server response
                reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
                sb = new StringBuilder();

                // Read Server Response
                while ((line = reader.readLine()) != null) {
                    // Append server response in string
                    sb.append(line);
                    //sb.append(line + "\n"); //this line causes error also...
                    Log.d("Returned Line", "is " + line);
                }
                reader.close();
                responseData = sb.toString();
                Log.d("Returned Data", "sb " + sb);

            }catch (IOException e) {
                //e.printStackTrace();
                //responseData = e.toString();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result){
            if (responseData.equals( "User Found." )) {
                message = "Welcome";
                Bundle bundle = new Bundle();//bundle the message and parse it to the next activity
                bundle.putString("dispMsg", message);//bundle the message using the variable dispMsg
                intent.putExtras(bundle);
                startActivity(intent);
                statusBar.setText(message);
            } else {
                message = "Incorrect Username or Password. Try again!";
                statusBar.setText(message);
            }
            super.onPostExecute(result);
        }
    }
}

谢谢大家!

相关问题