我正在尝试使用HttpUrlConnection从我的Android应用程序将json数据发送到php脚本,并获得响应。
Android代码
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'];
?>
我的代码是关于购买商品,使用它并在网络服务器上将新值发送到我的数据库。购买&amp;消费是好的,但我无法将值发送到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
感谢您的任何想法!
答案 0 :(得分:-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 **/
愿它能帮到你。