2
我試着用抽射Android應用發送POST請求託管在我的服務器上PHP腳本。當我得到響應代碼時,我得到Code 200 Successfull
,但在PHP腳本中爲$_POST
爲空。發送帶有凌空POST請求的PHP腳本
我的Android請求代碼:
try {
RequestQueue requestQueue = Volley.newRequestQueue(this);
String URL = getResources().getString(R.string.web_login);
JSONObject jsonBody = new JSONObject();
jsonBody.put("hello", "world");
jsonBody.put("username", username);
final String mRequestBody = jsonBody.toString();
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.i("LOG_VOLLEY", response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e("LOG_VOLLEY", error.toString());
}
}) {
@Override
public String getBodyContentType() {
return "text/plain; charset=utf-8";
}
@Override
public byte[] getBody() throws AuthFailureError {
try {
return mRequestBody == null ? null : mRequestBody.getBytes("utf-8");
} catch (UnsupportedEncodingException uee) {
VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", mRequestBody, "utf-8");
return null;
}
}
@Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
String responseString = "";
if (response != null) {
try {
responseString = new String(response.data, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
return Response.success(responseString, HttpHeaderParser.parseCacheHeaders(response));
}
};
requestQueue.add(stringRequest);
} catch (JSONException e) {
e.printStackTrace();
}
此代碼工作正常,但是當我得到的響應頭就包含下一PHP錯誤:
Undefined index: username
這裏是我的PHP腳本:
<?php
//Get post data from Android App
$name = $_POST['username'];
if (isset($name)){
$data = "OK";
header('Content-Type: text/plain');
echo $data;
}
?>
我在做什麼錯?
你發佈到的是,PHP腳本的網址是什麼?問題是在android側。 – mkaatman
@mkaatman是的,URL是正確的,因爲我得到了PHP錯誤的迴應。 – Hechi
嘗試'應用程序/ json;'在java –