Java 从Android发布到PHP文件的数据返回空字符串
我研究了有关这个主题的大量材料。我从他们所有人身上都学到了一些例子,但都没有用 我正在从Android应用程序向php文件发布数据(txtUsername和txtPassword) 此代码中的问题是,HTTPConnection将空字符串发布到php文件。 我使用了Uri字符串生成器和其他构建字符串的方法。。。它们都返回“已解析的空字符串” 主活动代码 * //创建GetText方法Java 从Android发布到PHP文件的数据返回空字符串,java,php,android,string,Java,Php,Android,String,我研究了有关这个主题的大量材料。我从他们所有人身上都学到了一些例子,但都没有用 我正在从Android应用程序向php文件发布数据(txtUsername和txtPassword) 此代码中的问题是,HTTPConnection将空字符串发布到php文件。 我使用了Uri字符串生成器和其他构建字符串的方法。。。它们都返回“已解析的空字符串” 主活动代码 * //创建GetText方法 private class GetText extends AsyncTask<Void,
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);
方法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;}
}
?>
//检查从回发数据返回的数据变量,然后将用户登录到下一个活动
if (Data.equals("User Found.")) {
///但此时,数据为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);
}
}
}
}
将您现在拥有的所有代码放在onPostExecute中该语句之后。现在,您甚至在异步任务开始发布之前就执行了该代码
username = un.getText().toString();//convert username and password to string and parse
password = pw.getText().toString();//them to variables
在onCreate()中为时过早。将这些行移到loginUser()。我非常感谢您的贡献和不辞辛劳的支持。 我已经找到了解决问题的办法 以下是文档的完整代码
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);
}
}
}
package com.example.examinationationportal;
导入android.content.Intent;
导入android.database.Cursor;
导入android.database.sqlite.SQLiteDatabase;
导入android.database.sqlite.SQLiteOpenHelper;
导入android.graphics.Color;
导入android.net.Uri;
导入android.os.AsyncTask;
导入android.provider.Settings;
导入android.support.v7.app.AppActivity;
导入android.os.Bundle;
导入android.support.v7.widget.Toolbar;
导入android.util.Log;
导入android.view.view;
导入android.widget.EditText;
导入android.widget.TextView;
导入android.app.IntentService;
导入android.app.pendingent;
导入org.apache.http.NameValuePair;
导入java.io.BufferedReader;
导入java.io.BufferedWriter;
导入java.io.IOException;
导入java.io.InputStreamReader;
导入java.io.OutputStream;
导入java.io.OutputStreamWriter;
导入java.io.UnsupportedEncodingException;
导入java.net.HttpURLConnection;
导入java.net.MalformedURLException;
导入java.net.URL;
导入java.net.URLConnection;
导入java.net.urlcoder;
导入java.util.ArrayList;
导入java.io.InputStream;
公共类MainActivity扩展了AppCompatActivity{
公共字符串消息=”;
公共字符串数据=”;
公共字符串responseData=“”;
公共字符串用户名=”;
公共字符串密码=”;
公共字符串数据=”;
公众意向;
公共图书馆;
公共弦线;
文本视图状态栏,标题登录;
编辑文本un,pw;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//初始化状态栏textview控件
状态栏=(TextView)findViewById(R.id.textViewStatusMsg);
titleLogin=(TextView)findViewById(R.id.textViewLogin);//此UI的标题文本
}
公共无效新用户(查看注册表){
Intent i=newintent(this,registerSerActivity.class);//为新用户启动ui
星触觉(i);
}
public void login用户(查看登录){//在用户点击登录按钮时调用
intent=newintent(this,DisplayWelcomeScreen.class);//启动ui
//获取用户定义的值
un=(EditText)findViewById(R.id.editTextUsername);//用户名字段
pw=(EditText)findViewById(R.id.editTextPassword);//密码字段
username=un.getText().toString();//将用户名和密码转换为字符串并解析
password=pw.getText().toString();//将它们转换为变量
新建GetText().execute();
}
//创建GetText方法
公共类GetText扩展AsyncTask{/}引发不受支持的CodingException{
@凌驾
受保护的Void doInBackground(Void…参数){
BufferedReader reader=null;
//发送数据
试一试{
//已定义用于发送数据的URL
URL=新URL(“http://www.naomiedify.com/school/test/login2.php");
//URLConnection con=url.openConnection();
HttpURLConnection con=(HttpURLConnection)url.openConnection();
con.setRequestProperty(“接受字符集”、“UTF-8”);
con.setRequestProperty(“内容类型”,“应用程序/x-www-form-urlencoded;字符集=UTF-8”);
con.setRequestMethod(“POST”);
con.setReadTimeout(10000);
con.设置连接超时(15000);
Uri.Builder=新的Uri.Builder()
.appendQueryParameter(“txtUserName”,用户名)
.appendQueryParameter(“txtPassword”,password)
附录参数(“CMB类型”、“能力倾向测试”);
字符串查询=builder.build().getEncodedQuery();
//发送POST数据请求
con.设置输出(真);
OutputStream os=con.getOutputStream();
//OutputStreamWriter wr=新的OutputStreamWriter(con.getOutputStream());
BufferedWriter wr=新的BufferedWriter(新的OutputStreamWriter(os,“UTF-8”));
wr.write(查询);
wr.flush();
wr.close();
os.close();
//获取服务器响应
reader=newbufferedReader(newInputStreamReader(con.getInputStream());
sb=新的StringBuilder();
//读取服务器响应
而((line=reader.readLine())!=null){
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);*/
}
}
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);
statusBar.setText(Data);
if (Data.equals("User Found.")) {
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);
}
}
}
}
new GetText().execute();
username = un.getText().toString();//convert username and password to string and parse
password = pw.getText().toString();//them to variables
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);
}
}
}