2013-07-11 25 views
1

我有一个应用程序可以将Android的名字和密码从Android发送到PHP。Android和PHP codeigniter之间的简单连接代码

我的Android代码:

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笨控制器

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但我不知道它在哪里,任何人都可以帮助我?

+0

什么是“问题”是什么呢? – DevZer0

+0

当我执行android应用程序什么也没有发生,显然它不与服务器连接,我该怎么办? – user2026521

+0

你的logcat输出说什么? – DevZer0

回答

3

您已使WebService在POST VARIALBLE中接受请求并以JSON格式给出响应。

我给你举例:

也许这将是对你有帮助:

控制器下面的完整代码在笨

class info_control extends CI_Controller { 

    //consrtuctor 
    public function __construct() 
    { 
     parent::__construct(); 
     /* 
     load you helper library 
     */ 
     /* 
     load you model 
     */ 

     $this->load->library('form_validation'); 
    } 

    function register_get() 
    { 
     /* What you have done that i don't know */ 
     /* 
     $json = array('status' => false); 
     if($this->input->post()==null){ 
      $this -> response($json, 200); 
     } 
     */ 

     /* This is Form Validation */ 
     $this->form_validation->set_rules('first_name', 'FirstName', 'valid_email|required'); 
     $this->form_validation->set_rules('last_name', 'LastName', 'required'); 
     $this->form_validation->set_rules('password', 'Password', 'required'); 

     /* Here you mistake $this->post('post var')*/ 
     $firstname = $this->input->post("first_name"); 
     $lastname = $this->input->post("last_name"); 
     $password = $this->input->post("password"); 

     /** YOUR PROCESS for REGISTER **/ 
     /* 
     LIKE 
     */ 
     if ($this->form_validation->run() == TRUE) 
     { 
      if(/* REGISTRATION SUCCESSFUL */) 
      { 
       $data = array('result' => 'success', 'msg' => 'Registered Successfully...'); 
      } 
      else 
      { 
       $data = array('result' => 'error', 'msg' => 'Email Already Used or Invalid - Unable to Create Account'); 
      } 
     } 
     else 
     { 
      $data = array('result' => 'error','msg' => preg_replace("/[\n\r]/",".",strip_tags(validation_errors()))); 
     } 

     echo json_encode($data); 

     /* 
     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); 
     */ 
    } 

现在的Android代码: 你必须发送数据像:

static InputStream is; 
    static String result; 
    static JSONObject jsonObject; 

    static HttpClient httpClient; 
    static HttpPost httpPost; 

    static List<NameValuePair> pairs; 

    static HttpResponse response; 
    static HttpEntity entity; 

private static void init() { 
    // TODO Auto-generated constructor stub 
    is = null; 
    result = ""; 
    jsonObject = null; 
    httpPost = null; 
    httpClient = new DefaultHttpClient(); 
} 

private static String getResult(InputStream is) { 
    // TODO Auto-generated method stub 
    BufferedReader reader; 
    StringBuilder stringBuilder = null; 

    try { 
     reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8); 

     stringBuilder = new StringBuilder(); 
     String line = null; 

     while ((line = reader.readLine()) != null) { 
      stringBuilder.append(line + "\n"); 
     } 
     is.close(); 

    } catch (IOException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 
    return stringBuilder.toString();  
} 

//for Register Employee 
    public static JSONObject registerUser(String url, String firstNameString, String lastNameString, String passwordString) { 
     // TODO Auto-generated method stub 
     try{ 
      init(); 

      Log.d("msg", "URL : "+url); 
      httpPost = new HttpPost(url.toString()); 

      Log.d("msg", "post : "+httpPost); 

      pairs = new ArrayList<NameValuePair>(); 

      pairs.add(new BasicNameValuePair("firstname", firstNameString)); 
      pairs.add(new BasicNameValuePair("lastname", lastNameString)); 
      pairs.add(new BasicNameValuePair("password", passwordString)); 

      httpPost.setEntity(new UrlEncodedFormEntity(pairs,HTTP.UTF_8)); 

      Log.d("msg", "httppost : "+httpPost.toString()); 

      response = httpClient.execute(httpPost); 

      Log.d("msg", "res : "+response.getStatusLine().getStatusCode()); 

      entity = response.getEntity(); 

      is = entity.getContent(); 

      Log.d("msg", ""+is); 
      /*//** Convert response to string **/ 
      result = getResult(is); 

      jsonObject = new JSONObject(result); 
      Log.d("msg", "jsonObj : "+jsonObject); 
     } 
     catch(ClientProtocolException e){ 
      Log.e("log_tag", "Error in Client Protocol : "+e.toString()); 
     }catch(JSONException e){ 
      Log.e("log_tag", "Error Parsing data "+e.toString()); 
     }catch(Exception e){ 
      Log.e("log_tag", "Error in HTTP Connection : "+e.toString()); 
     } 
     return jsonObject; 
    } 

你喜欢这个岗位,愿平安我,如果您有任何疑问:

编码快乐...投票最多......

0

这个工作对我来说:

的JSON在PHP返回是“[{\”pk_accident \“:\”25 \“},{\”pk_accident \“:\”68 \“}]”,在init和final字符串中的白色引号以及反斜杠。

但是,这是建立jSONArray,然后whitin Android应用的解决方法是删除了JSON结构中所有数据的问题:

public ArrayList<String> getDataJSON(String phpJsonString){ 
    ArrayList<String> listArrayView= new ArrayList<String>(); 
    try { 

     int posIni = phpJsonString.indexOf('['); 
     int posFin = phpJsonString.indexOf(']') + 1; 
     phpJsonString = phpJsonString.substring(posIni,posFin); 
     phpJsonString = phpJsonString.replace("\\", ""); 
     JSONArray json= new JSONArray(phpJsonString); 
     String text=""; 
     for (int i=0; i<json.length();i++){ 
      text = json.getJSONObject(i).getString("value1") +" - "+ 
        json.getJSONObject(i).getString("value2"); 
      listArrayView.add(text); 
     } 
    } catch (Exception e) { 
     // TODO: handle exception 
    } 
    return listArrayView; 
}