我想從JSON字符串從android應用程序發送到PHP服務器。雖然我沒有在服務器端實現任何合理的編碼,但足以看到會發生什麼。讓我告訴你我的Android代碼和PHP代碼。問題是我沒有得到任何東西在服務器上。根本沒有迴應。我實際上在本地服務器上用Python代碼驗證了這個程序,並且我收到了預期的輸出,但在PHP上什麼都沒有。由於我是PHP新手,一定有一些我不知道的東西。Android到PHP服務器沒有收到數據
這是ANDROID代碼:這是運行在不同的線程。
public void onSync(View v) throws JSONException, IOException {
//This will call onSync function.
handler.sendEmptyMessage(MSG_SYNC);
}
protected void onSync_() {
String json = null;
try {
json = database.getAllAsJSONString();
} catch (JSONException e) {
Log.e("", "Could not convert to JSON", e);
}
HttpURLConnection urlConnection = null;
OutputStream out = null;
try {
byte[] jsonBytes = json.getBytes("UTF-8");
URL url = new URL("http://androidapplicati.base.pk");
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setDoOutput(true);
urlConnection.setFixedLengthStreamingMode(jsonBytes.length);
urlConnection
.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestProperty("Content-Length",
String.valueOf(jsonBytes.length));
out = urlConnection.getOutputStream();
out.write(jsonBytes);
out.flush();
urlConnection.getInputStream().read();
} catch (MalformedURLException e) {
Log.e("", "Error posting data(1)", e);
} catch (IOException e) {
Log.e("", "Error posting data(2)", e);
} finally {
try {
out.close();
} catch (Exception e) {
Log.w("", "Error closing stream", e);
}
urlConnection.disconnect();
}
這裏是PHP代碼。
<?php
print_r($_REQUEST);
var_dump($_REQUEST);
?>
'NetworkOnMainThreadException'請看看的AsyncTask使HTTP調用 –
我調用不同的線程中此功能。所以這個調用不在主線程中。 – Shah