安卓&PHP:使用PHP将数据从Android发布到mysql数据库
我需要将登录/注册数据从Android应用传递到localhost上的mysql数据库.我仍在学习过程中,上个星期对此有疑问.我读了数十页的问题和回答了Stack Overflow,并尝试了所有方法,但我无法解决此问题.您能在代码中指出我的问题吗,关于php和JSON我还是新手.
I need to pass login/register data from Android app to mysql database on localhost. I'm still in learning process, and have problem with this for last week. I read dozens of pages, questions & answers on Stack Overflow and tried everything but I just can't get this to work. Can You please point me the problem in my code, I'm still newbie regarding php and JSON.
Android,活动和应用程序;AsyncTask类:
Android, Activity & AsyncTask Class:
package com.example.mario.datadrivenassignmenttwo;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
public class DbManager extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
}
public void register(View v) {
EditText uname = (EditText) findViewById(R.id.username);
EditText pw = (EditText) findViewById(R.id.password);
String username = uname.getText().toString();
System.out.println("username is: " + username);
String password = pw.getText().toString();
System.out.println("password is: " + password);
Uploader task = new Uploader();
task.execute(new String[] { "http://10.0.2.2/user_db/senddata.php", username, password });
}
public class Uploader extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
/*
String response = "Finished";
try {
postHttpContent(params[0],params[1],params[2]);
} catch (IOException e) {
Log.e("error", e.toString());
}
return response;
*/
try {
String urlParam = params[0];
String username = params[1];
String password = params[2];
String charset = java.nio.charset.StandardCharsets.UTF_8.name();
String query = String.format("username=%s&password=%s", URLEncoder.encode(username, charset), URLEncoder.encode(password, charset));
/*
URLConnection conn = new URL(urlParam).openConnection();
conn.setDoOutput(true);
conn.setRequestProperty("Accept-Charset", charset);
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + charset);
OutputStream output = conn.getOutputStream();
output.write(query.getBytes(charset));
output.flush();
output.close();
*/
URL url = new URL(urlParam);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
writer.write(query);
writer.close();
if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
System.out.println("It's ok!");
System.out.println(query);
} else {
System.out.println("Error code there");
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "Finished";
}
@Override
protected void onPostExecute(String result) {
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();
}
}
}
还有我的PHP:
<?php
// connect to database
$hostname = "localhost";
$username = "root";
$password = "root";
$dbname = "user_db";
$link = new mysqli($hostname, $username, $password, $dbname);
// get the JSONArray the app sends
$contents = file_get_contents('php://input');
$jsonArray = json_decode($contents, true);
$jsonCount = count($jsonArray);
for ($i = 0; $i < $jsonCount; $i++) {
$item = $jsonArray[$i];
$itemUsername = utf8_decode($item['username']);
$itemPassword = utf8_decode($item['password']);
// parse the other json attributes here like the one above
$sql = "INSERT INTO users (username, password) VALUES ('$itemUsername', '$itemPassword')";
if ($link->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $link->error;
}
}
$link->close();
?>
有很多注释的代码,这是我尝试过的所有内容,还有一些其他代码,但无济于事.我还尝试将所有连接和其余连接放到一个方法中,并在AsyncTask类中调用该方法,但同样失败.由于我不了解PHP,因此不确定问题是否出在我的Android代码或PHP文件中.
There is a lot of commented code, that's all I have tried, and some other code as well, but nothing works. I also tried putting all the connection and rest into one method and calling that method inside AsyncTask class, that failed aswell. Since I don't know PHP, I'm not sure if the problem is in my Android code or PHP file.
非常感谢.
我在10分钟前就知道了.我现在正在发布新代码,它可以正常工作.
I figured it out 10minutes ago. I'm posting new code now, and it works.
package com.example.korisnik.test;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class DbManager extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
}
public void register(View v) {
EditText uname = (EditText) findViewById(R.id.username);
EditText pw = (EditText) findViewById(R.id.password);
String username = uname.getText().toString();
String password = pw.getText().toString();
System.out.println("Username is: " + username + " ,and password is: " + password);
Uploader task = new Uploader();
task.execute(new String[] { "http://10.0.2.2/user_db/senddata.php", username, password });
}
public class Uploader extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
String response = null;
try {
response += postHttpContent(params[0],params[1],params[2]);
} catch (IOException e) {
System.out.println("IO Error");
Log.e("error", e.toString());
} catch (JSONException e) {
System.out.println("JSON Error");
e.printStackTrace();
}
return response;
}
@Override
protected void onPostExecute(String result) {
System.out.println(result);
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();
}
public String postHttpContent(String urlStr, String user, String pass) throws IOException, JSONException {
String response = "";
URL url = new URL(urlStr);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
httpConn.setDoOutput(true);
httpConn.setDoInput(true);
httpConn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
httpConn.setRequestMethod("POST");
JSONObject userdata = new JSONObject();
userdata.put("username",user);
userdata.put("password", pass);
JSONArray data = new JSONArray();
data.put(userdata);
System.out.println("Array is: " + data);
try {
DataOutputStream localDataOutputStream = new DataOutputStream(httpConn.getOutputStream());
localDataOutputStream.writeBytes(data.toString());
localDataOutputStream.flush();
localDataOutputStream.close();
System.out.println("Data writting: " + data);
} catch (IOException e) {
e.printStackTrace();
System.out.println("Data Output error");
}
int responseCode = httpConn.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(httpConn.getInputStream()));
do {
line = br.readLine();
response += line;
} while ((line = br.readLine()) != null);
} else {
response = "Error ";
throw new IOException();
}
return response + " * Uploaded!";
}
}
}
我使用JSONObject并将用户名和密码的键/值对放入其中.比我把那个JSONObject放在JSONArray中(我知道它只是一个JSONObject,我不必将它放入JSONArray中,但是由于我的PHP代码是为JSONArray设计的,并且我对PHP不太满意,所以我认为将JSONObject放入JSONArray比更改我不太了解的PHP代码要容易得多.
I used JSONObject and put key/value pairs of username and password in it. Than I put that JSONObject in JSONArray (I know it's just one JSONObject, and I didn't have to put it into JSONArray, but since my PHP code is "designed" for JSONArray, and I'm not good with PHP, I figured it's easier to put JSONObject into JSONArray, than to change PHP code which I don't understand very well.
第二个更改是使用"DataOutputStream"而不是"OutputStreamWriter".
Second change is using "DataOutputStream" instead of "OutputStreamWriter".