Ich habe umfangreiche Materialien zu diesem Thema recherchiert. Ich habe Beispiele von ihnen alle vergeblich verfolgt.Posted Daten von Android zu PHP-Datei zurückgegeben leere Zeichenfolgen
Ich poste Daten (txtUsername und txtPassword) zu php Datei von Android App.
Das Problem in diesem Code ist, Httpconnection Beiträge leere Zeichenfolge zu PHP-Datei. Ich habe Uri String Builder verwendet, und andere Methoden zum Erstellen von Strings ... sie alle geben "Leere Strings Parsed" zurück.
DIE MAINACTIVITY CODE
*
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-Methode erstellen
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);
// dies sind die Daten zu PHP-Server beachten // bitte zu senden, dass , Ich habe verschiedene Methoden verwendet, um Strings zu erstellen, die an den Server gesendet werden, aber die Strings werden getrimmt, bevor sie gepostet werden. Ich kann nicht Namevaluepair verwenden, weil es in Android 2.3 Zum Beispiel ist veraltet: Methode 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");
Methode 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-Daten Anfrage senden
con.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream());
wr.write(query);
wr.flush();
wr.close();
// Erhalten Sie die Serverantwort
reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
// lesen Server-Antwort
while((line = reader.readLine()) != null) {
// server in Zeichenfolge anhängen Antwort
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;
}
// das Ereignis OnPostExecute starten
@Override
protected void onPostExecute(Void result){
statusBar.setText(responseData);
super.onPostExecute(result);
}
}
// Anmeldung Code für onClick Ereignis
public void loginUser(View login) {// Called when the user taps the login button
Intent intent = new Intent(this, DisplayWelcomeScreen.class);//start the ui
// erhalten die Antwort von PHP-Server
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-Code [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>
* Bitte helfen Sie mir ... Ich weiß nicht, wohin ich gegangen bin falsch. TIPP: Ich bin neu in Android-Programmierung.
Vielen Dank.
Dies ist der neueste Code .... trotzdem gibt PHP immer noch "Empty Strings Parsed" zurück.
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);
}
}
}
Ich habe den gesamten Code neu bearbeitet ... unten ... Das Ergebnis bleibt nach wie vor "Empty Strings" in PHP geschrieben.
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);*/
}
}
Liebe helfende Freunde, ich um meine App-Codes gearbeitet haben, wie Sie alle vorgeschlagen ... Die App ist in der Lage Daten zu PHP-Server zu senden und auch Daten empfangen.
Aber da kann ich die Daten nicht zu StartActivity (Absicht) auswerten. Bitte hier ist der Code unten ...
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);
// an dieser Stelle wertet Daten nicht null
statusBar.setText(Data);
// die Variable aus den gebuchten Rück Daten dann Login Benutzer zurückgegeben Daten überprüfen zur nächsten Aktivität.
if (Data.equals("User Found.")) {
/// aber an diesem Punkt sind die Daten null und der else {} Block ausgewertet wird.
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);
}
}
}
}
Ich würde beginnen, indem ich die * tatsächlichen * URLs ansehe, die in der Anfrage gesendet wurden, und überprüfe, um zu sehen, was die Parameter tatsächlich sind und ob sie korrekt codiert wurden. –
'os.close();' ?? Ich kann nicht glauben, dass du danach aus dem Inputstream lesen kannst. Besser entfernen. – greenapps
'Zeichenfolge query = builder.build(). GetEncodedQuery();'. Bitte protokollieren Sie diese Abfragevariable und teilen Sie uns mit, was Sie sehen. – greenapps