2011-05-28 90 views
0

我想提交一些格式爲JSONObject的數據到Web服務器。我的理解是,這是用android上的httpclient和服務器上的php文件完成的。如果不是這種情況到此爲止和指正,否則這裏就是我如何嘗試發送數據:如何將JSONObject傳遞給PHP文件?

HttpClient httpclient = new DefaultHttpClient(); 
      HttpPost httppost = new HttpPost("http://myhost/data.php"); 
      try { 
       String UN = username.getText().toString(); 
       String PW = password.getText().toString(); 
       String jString = "{\"login\": { \"username\": \""+UN + "\",\"password\": \""+PW+"\"}}"; 
       JSONDATA = new JSONObject(jString); 
       //JSONDATA = new JSONObject(); 
       //JSONDATA.put("username", UN); 
       //JSONDATA.put("password", PW); 

我應該使用:httppost.setEntity(新UrlEncodedFormEntity(JSONDATA));

或者我應該做它像這樣:

   StringEntity se = new StringEntity(JSONDATA.toString()); 
       se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); 
       HttpEntity entity; 
       entity = se; 
       httppost.setEntity(entity); 
       HttpResponse response; 
       response = httpclient.execute(httppost); 

回答

3

真正的問題是如何你打算拉出來的數據在服務器上?你的PHP是什麼樣的?什麼可能是最簡單的就是剛剛通過JSON作爲參數:

HttpClient httpclient = new DefaultHttpClient(); 
HttpPost httppost = new HttpPost("http://myhost/data.php"); 
try { 
    String UN = username.getText().toString(); 
    String PW = password.getText().toString(); 
    String jString = "{\"login\": { \"username\": \""+UN + "\",\"password\":\""+PW+"\"}}"; 
    List <NameValuePair> nvps = new ArrayList <NameValuePair>(); 
    nvps.add(new BasicNameValuePair("value", jString)); 
    httppost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));     

    HttpResponse response; 
    response = httpclient.execute(httppost); 

,然後在服務器端,你可以做

<?php 
    $obj = json_decode($_POST['value']); 

進行檢索。