2013-05-08 33 views
0

我正在嘗試爲我的android應用程序構建一個web服務。 但我有問題發送parametres到php。 我正在使用這些代碼塊到Http-Post。如何從Android到PHP獲取json對象

public String requestJson(String method, JSONObject parameters) { 
     try { 
      int TIMEOUT_MILLISEC = 10000; 
      HttpParams httpParams = new BasicHttpParams(); 
      HttpConnectionParams.setConnectionTimeout(httpParams, TIMEOUT_MILLISEC); 
      HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC); 
      HttpClient client = new DefaultHttpClient(httpParams); 

      String tmpUrl = serviceUrl.trim() + (serviceUrl.trim().endsWith("/") ? method : "/" + method); 

      HttpPost request = new HttpPost(tmpUrl); 

      request.setHeader(HTTP.CONTENT_TYPE, "application/json; charset=utf-8"); 

      if (parameters != null) 
      { 
       request.setEntity(new StringEntity(parameters.toString(), HTTP.UTF_8)); 
      } 

      HttpResponse response = client.execute(request); 

      final int statusCode = response.getStatusLine().getStatusCode(); 
      final String jsonResponse = EntityUtils.toString(response.getEntity()); 

      if (statusCode != HttpStatus.SC_OK) { 
       Log.w(TAG, "Error in web request: " + statusCode); 
       Log.w(TAG, jsonResponse); 
       return null; 
      } else { 
       Log.i(TAG, jsonResponse); 
       return jsonResponse; 
      } 
     } catch (Exception e) { 
      Log.e(TAG, "Error in fetching JSON due to -> " + e.toString()); 
     } 
     return null; 
    } 


    public String testFunction() { 
     try { 
      JSONObject param = new JSONObject(); 
      param.put("testID", 123); 
      JsonCevabi = requestJson("test.php", param); 

      if (JsonCevabi != null) { 
       JSONObject jo = new JSONObject(JsonCevabi); 
       JSONArray ja = new JSONArray(jo.getString("d")); 

       @SuppressWarnings("unchecked") 
       List<SampleEntity> resultList = (List<SampleEntity>) new Gson().fromJson(ja.toString(), new TypeToken<List<SampleEntity>>() { 
       }.getType()); 
       return JsonCevabi; 
      } 
      else 
       return null; 
     } catch (Exception e) { 
      return null; 
     } 
    } 

而我的php代碼是這樣的;

<?php 

$id = json_decode($_POST['testID']); 


$json = "{d:[{sample1:'".$id."',sample2:'value12'}]}"; 
$response = $_GET["callback"] . $json; 
echo $response; 
?> 

我想要做的是發送TestID參數爲php。而且我正在費力地讓我回到這個價值。

但我正在逐漸{d:[{SAMPLE1: '',SAMPLE2: 'value12'}]}

我要的是{d:[{SAMPLE1: '123',SAMPLE2: 'value12' }]}

我缺少什麼?

編輯:我發現了類似的問題,但沒有幫助; Android JSON HttpClient to send data to PHP server with HttpResponse

回答

2

由於@chandresh_cool表示POST參數存在問題。 你應該像這樣編輯你的StringEntity: new StringEntity("testID="+parameters.toString(), HTTP.UTF_8)

然後在你的服務器中的$ id變量包含了解碼的JSON,所以你應該做的:

$id = json_decode($_POST['testID'], true); 
$json = "{d:[{sample1:'".$id['testID']."',sample2:'value12'}]}"; 
+0

我試過你說的。但沒有運氣。我必須做錯事。 – 2013-05-08 20:56:01

1

貌似

$_POST['testID'] 

是一個問題。你確實使用post方法發送變量嗎?

+0

我想在這樣的testFunction; JSONObject param = new JSONObject(); param.put(「testID」,123); – 2013-05-08 18:50:28

1

更改PHP代碼以下解決我的問題。

<?php 
$postdata = $HTTP_RAW_POST_DATA; 
$data = json_decode($postdata); 
$id = $data->testID; 
$json = "{d:[{sample1:'".$id."',sample2:'value12'}]}"; 
$response = $_GET["callback"] . $json; 
echo $response; 
?> 

http://fahmirahman.wordpress.com/2011/04/26/the-simplest-way-to-post-parameters-between-android-and-php/

更詳細的信息可以發現上面的鏈接。

+1

經過一番調查後,我發現$ _POST只在內容類型是'application/x-www-form-urlencoded'或'multipart/form-data' – user2340612 2013-05-08 22:15:20

1
@Java Code to send data: 

StringEntity entity = new StringEntity("jsonRequest="+data.toString(), HTTP.UTF_8);     
httpPost.setEntity(entity); 
response = httpClient.execute(httpPost); 
HttpEntity entityPost = response.getEntity(); 
result = EntityUtils.toString(entityPost); 
return result; 

@PHP code to receive data 
$jsonRequest = json_decode($_REQUEST['jsonRequest'], true); 

@check if the data is coming we can log the contents 
date_default_timezone_set('EST'); 

ini_set("log_errors", 1); 
ini_set("error_log", "site.log"); 
error_log("Hello, errors!".print_r($jsonRequest[id],1));