且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

安卓&PHP:使用PHP将数据从Android发布到mysql数据库

更新时间:2022-04-24 03:20:53

我在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".