2015-06-22 66 views
3

我想從我的Android應用程序使用HttpClient發送json數據到php腳本,並獲得響應。Android HttpClient響應

的Android代碼

private void sendPurchase(String SKU) throws IOException{  
    Log.e("sendPurchase","Inside sendPurchase"); 
    final SharedPreferences prefs = getGCMPreferences(getApplicationContext()); 
    int pur_user = prefs.getInt("C_user", Integer.MIN_VALUE); 
    InputStream inputStream = null; 
    String result = ""; 
    HttpClient httpclient = new DefaultHttpClient(); 
    HttpPost httpPost = new HttpPost("http://www.*.com/includes/purchase.php");    
    JSONObject json = new JSONObject();    
    try { 
     json.put("PUR_sku", SKU); 
     json.put("PUR_user", pur_user); 
    } catch (JSONException e) { Log.e("SendPurchase","Problem with Json Object"); }  
    Log.i("JSONObject", json.toString()); 
    StringEntity se = new StringEntity(json.toString(), HTTP.UTF_8); 
    httpPost.setEntity(se); 
    httpPost.setHeader("Accept", "application/json"); 
    httpPost.setHeader("Content-type", "application/json");   
    HttpResponse httpResponse = httpclient.execute(httpPost); 
    inputStream = httpResponse.getEntity().getContent(); 
    if(inputStream != null){ result = convertInputStreamToString(inputStream); } 
    else{result = "Did not work!"; } 
    Log.e("RESULT",result);  
} 

private static String convertInputStreamToString(InputStream inputStream) throws IOException{ 
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); 
    String line = ""; 
    String result = ""; 
    while((line = bufferedReader.readLine()) != null) 
     result += line; 
    inputStream.close(); 
    return result; 
} 

而且PHP腳本

<? 
$auth=0; 
require('./connexion.php'); 
$data = file_get_contents('php://input'); 
//$data = '{"PUR_sku":"singleone","PUR_user":"3"}'; 
$json = json_decode($data,true); 
/* Some database stuff ... */ 
echo "Retour ".print_r($json)." et ".$json['PUR_sku']." et ".$json['PUR_user']; 
?> 

當我啓動的應用程序和執行sendPurchase功能,它似乎是確定,直到HttpPost的執行。在logcat中,我得到了所有具有正確參數的日誌,除了最後一個沒有出現的日誌「RESULT」。 這就是爲什麼我認爲HttpPost執行出現問題,但實際上我不知道問題來自應用程序端還是php腳本端... 當我在Web瀏覽器中單獨執行php腳本時,用第二個數據行取代第一個數據行,一切都很好。但是,當它來自應用程序它不好... Json對象發送(我希望)的腳本似乎也可以:{「PUR_user」:3,「PUR_sku」:「singleone」}

(the sendPurchase函數在後臺執行)。

任何關於我在做什麼錯的想法?謝謝 !

/EDIT/

這裏是@RyuZz溶液logcat的。 我的代碼是關於購買一個項目,使用它並向Web服務器上的數據庫發送新值。購買&消耗正常,但我無法將值發送到Web服務器。 而且,當我在網絡瀏覽器中單獨執行php腳本時,將第一個$數據行替換爲第二個數據行,一切正常。 請注意,我有另一個類似的代碼註冊用戶GCM,使用HttpClient,並且該代碼工作正常。

06-25 14:07:12.968: D/IabHelper(21833): Successfully consumed sku: singleconf 
06-25 14:07:12.968: D/IabHelper(21833): Ending async operation: consume 
06-25 14:07:12.979: D/CONSUME(21833): Consumption finished. Purchase: PurchaseInfo(type:inapp):{"orderId":"12999763169054705758.1353445524837889","packageName":"com.*.*","productId":"singleconf","purchaseTime":1435234296875,"purchaseState":0,"purchaseToken":"bohbcbiigcbidfficbikebnk.AO-J1OzuQ_SsNTG1h9MtUvbaPc3PeN9nBHG-qBOE82ao1rTDFNrgA7tYQcMdECxCVFrrZEn_QifQ28OcIupyesZI-5cjDILFODYpBEaeqMfE0wCAeMFkJLfNUK_TsKPMj7F2sBDdgOYx"}, result: IabResult: Successful consume of sku singleconf (response: 0:OK) 
06-25 14:07:12.979: D/CONSUME(21833): You bought & consumed a single conf 
06-25 14:07:12.979: D/CONSUME(21833): End consumption flow. 
06-25 14:07:12.979: E/Purchase Background(21833): Inside doInBackground 
06-25 14:07:12.979: E/sendPurchase(21833): Failed to send HTTP POST request due to: java.lang.NullPointerException 
+0

您是否獲得了日誌'「沒有工作!」'? –

+0

@Heyyou不,我沒有看到日誌「沒有工作」... –

+0

請問您可以在您的代碼中包含日誌嗎? –

回答

2

你可以試試下面的,而不是HttpClient的這無論如何棄用:

try{ 
    int pur_user = prefs.getInt("C_user", Integer.MIN_VALUE); 

    URL url = new URL("http://www.*.com/includes/purchase.php"); 
    HttpURLConnection connection = (HttpURLConnection) url.openConnection(); 
    connection.setDoOutput(true); 
    connection.setDoInput(true); 
    connection.setRequestProperty("Content-Type", "application/json"); 
    connection.setRequestProperty("Accept", "application/json"); 
    connection.setRequestMethod("POST"); 

    JSONObject jsonObject = new JSONObject(); 
    jsonObject.put("PUR_sku", SKU); 
    jsonObject.put("PUR_user", pur_user); 

    //convert JSONObject to JSON to String 
    json = jsonObject.toString(); 

    OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream()); 
    writer.write(json); 
    writer.close(); 

    responseCode = connection.getResponseCode(); 

    if(responseCode == 200) { 

     InputStream content = connection.getInputStream(); 
     try { 

      BufferedReader reader = new BufferedReader(new InputStreamReader(content, "UTF-8"), 8); 
      StringBuilder sb = new StringBuilder(); 

      String line; 
      while ((line = reader.readLine()) != null) 
      { 
       sb.append(line).append("\n"); 
      } 
      result = sb.toString(); 

      //TODO get your stuff from result 

      content.close(); 
     } catch (Exception ex) { 
      Log.e(TAG, "Failed to parse JSON due to: " + ex); 
     } finally { 
      connection.disconnect(); 
     } 
    } else { 
     Log.e(TAG, "Server responded with status code: " + responseCode); 
    } 
} catch(Exception ex) { 
    Log.e(TAG, "Failed to send HTTP POST request due to: " + ex); 
} 

如果不工作,請張貼logcat的。

不要忘記實現您的清單所需的權限:

<uses-permission 
    android:name="android.permission.INTERNET" /> 
+1

我更喜歡你如何追加'sb',然後使用'ToString'。 –

+0

嗨@RyuZz我試過你的代碼,並得到「無法發送HTTP POST請求,由於:java.lang.NullPointerException」在logcat –

+0

@MatthieuMarcé我認爲你的服務器端有問題,你可以使用RESTful服務從應用程序接收您的數據。請發佈完整的logcat – RyuZz