我有一个应用程序将名字和姓氏和密码从 Android 发送到 PHP。
我的安卓代码:
package com.example.com.tourism;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class SignUp extends Activity{
EditText first,last,birth ,pass;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sign_up);
Button signUp=(Button)findViewById(R.id.sign_up);
first =(EditText) findViewById(R.id.edfname);
last =(EditText) findViewById(R.id.edlname);
pass =(EditText) findViewById(R.id.edpass);
signUp.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
String firstn = first.getText().toString();
String lastn = last.getText().toString();
String passw = pass.getText().toString();
try {
JSONObject json = new JSONObject();
json.put("first_name", firstn);
json.put("last_name", lastn);
json.put("password", passw);
postData(json);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
public void postData(JSONObject json) throws JSONException {
HttpClient httpclient = new DefaultHttpClient();
try {
HttpPost httppost = new HttpPost("http://10.0.0.2:3784/tourism/index.php/site/register");
List<NameValuePair> nvp = new ArrayList<NameValuePair>(2);
nvp.add(new BasicNameValuePair("json", json.toString()));
//httppost.setHeader("Content-type", "application/json");
httppost.setEntity(new UrlEncodedFormEntity(nvp));
HttpResponse response = httpclient.execute(httppost);
if(response != null) {
InputStream is = response.getEntity().getContent();
//input stream is response that can be shown back on android
}
}catch (Exception e) {
e.printStackTrace();`enter code here`
}
}
}
并且在 php codeigniter 控制器中接收优先信息的函数是
function register_get()
{
$json = array('status' => false );
if($this->input->post()==null){
$this -> response($json, 200);
}
$firstname = $this->post("first_name");
$lastname = $this->post("last_name");
$password = $this->post("password");
if(!$firstname || !$lastname || !$password){
$json['status'] = "wrong insert";
$this -> response($json, 200);
}
$this->load->model('Data_model');
$result = $this->Data_model->search($firstname, $lastname);
if($result)
{
$this->Data_model->insert($firstname,$lastname,$password);
$json['status'] = true;
}
// here if false..
$this -> response($json, 200);
}
PHP代码我尝试了它,它工作我认为问题来自android,但我不知道它在哪里,谁能帮助我???