安卓HttpClient响应

3

我试图使用HttpClient从我的Android应用程序向php脚本发送json数据,并获取响应。

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函数时,除了最后一个“RESULT”日志之外,logcat中的所有日志都显示正确的参数。因此,我认为HttpPost的执行出了问题,但实际上我不知道问题是来自应用程序方面还是php脚本方面... 当我在Web浏览器中单独执行php脚本,并将第一个$data行替换为第二个行时,一切都正常。但是当来自应用程序时就不正常了... 发送到脚本的Json对象(我希望)似乎也没问题:{"PUR_user":3,"PUR_sku":"singleone"}
(sendPurchase函数在后台执行)
有关我做错了什么的任何想法吗?谢谢!
/编辑/
这是@RyuZz解决方案的logcat。 我的代码是关于购买物品,消耗它并将新值发送到我的Web服务器上的数据库。购买和消耗正常,但我无法将值发送到Web服务器。再次注意,我有另一个类似的代码用于向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

@嘿,你好,我没有收到日志“没有起作用”... - Matthieu Marcé
1个回答

2
您可以尝试以下替代方案,而不是已经被弃用的HttpClient:
您可以尝试使用以下替代方案,而不是已经被弃用的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" />

嗨@RyuZz,我尝试了你的代码并在Logcat中得到了“由于java.lang.NullPointerException而无法发送HTTP POST请求”的错误信息。 - Matthieu Marcé
@Matthieu Marcé,我认为你的服务器端出了问题,你可以使用RESTful服务从应用程序接收数据。请发布完整的logcat。 - RyuZz
好的 @RyuZz,我已经编辑了我的问题,你现在可以看到logcat和解释。 - Matthieu Marcé

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接