【问题标题】:Android HttpUrlConnection responseAndroid HttpUrlConnection 响应
【发布时间】:2015-07-07 21:34:15
【问题描述】:

我正在尝试使用 HttpUrlConnection 从我的 Android 应用程序将 json 数据发送到 php 脚本,并获得响应。

安卓代码

private void sendPurchase(String SKU) throws IOException{       
    try{
        int pur_user = prefs.getInt("CONF_user", Integer.MIN_VALUE);
        URL url = new URL("http://www.example.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);
        String json = jsonObject.toString();
        OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
        writer.write(json);
        writer.close();
        int 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"); }
                Log.e("sendPruchase",sb.toString());
                content.close();
            } catch (Exception ex) { Log.e("sendPurchase", "Failed to parse JSON due to: " + ex); } finally { connection.disconnect(); }
        } else { Log.e("sendPurchase", "Server responded with status code: " + responseCode); }
    } catch(Exception ex) { Log.e("sendPurchase", "Failed to send HTTP POST request due to: " + ex); }
}

还有 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'];
?>

我的代码是关于购买物品、使用它并将新值发送到我在 Web 服务器上的数据库。购买和消费没问题,但我无法将值发送到 Web 服务器。 同样,当我在网络浏览器中单独执行 php 脚本时,将第一行 $data 替换为第二行(参见脚本),一切正常。 请注意,我还有另一个类似的代码可以将用户注册到 GCM,并且该代码工作正常。

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

感谢您的任何想法!

【问题讨论】:

  • 能否将e.printStackTrace() 添加到最后的catch 子句中?然后在再次运行您的应用程序后添加整个堆栈跟踪
  • 06-25 14:07:12.979: E/sendPurchase(21833): 发送 HTTP POST 请求失败,原因是:java.lang.NullPointerException
  • @AnoopM 这只是他的自定义异常消息,它没有说明 NPE 发生的位置。
  • 你能告诉我SKUString
  • 我添加了 e.printStackTrace() 并更改了 sendPurchase 方法的调用方式(为了避免所有购买流程),现在我收到一个错误“服务器响应状态代码:500” ...

标签: php android httpurlconnection


【解决方案1】:

Android 端:

private void sendPurchase(String SKU) {

    /** 
     * Initialize All Variables
     */

    httpPost = new HttpPost(url.toString());

    pairs = new ArrayList<NameValuePair>();

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

    pairs.add(new BasicNameValuePair("data", jsonObject.toString()));

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

    response = httpClient.execute(httpPost);

    entity = response.getEntity();
    is = entity.getContent();

    /* Convert response to string */
    result = getResult(is);

    Log.d(TAG, "Response of Send Result : " + result);
}

PHP 端:

$data = json_decode($this->input->post('data'), true);

/** Your Process **/ 

希望对你有帮助。

【讨论】:

  • 出了点问题,我收到此错误“无法发送 HTTP POST 请求,原因是:java.lang.ClassCastException:org.apache.http.message.BasicHttpResponse 无法转换为 java.io.InputStream "
  • 我更正了这个问题,但真正的问题似乎来自 PHP 方面。 I posted a new question here if you want to take a look
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-02-12
  • 2012-07-20
  • 1970-01-01
  • 2012-02-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多