Im Versuch POST-Anfrage mit Volley von Android App zu PHP-Skript zu senden auf meinem Server gehostet. Wenn ich den Antwortcode bekomme, bekomme ich Code 200 Successfull
aber $_POST
in PHP-Skript ist leer.Senden eine POST-Anfrage mit Volley zu PHP Script
Mein Android Request-Code:
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();
}
Dieser Code funktioniert gut, aber wenn ich den Antwort-Header erhalten enthält es die nächsten PHP-Fehler:
Undefined index: username
Hier ist mein PHP-Skript:
<?php
//Get post data from Android App
$name = $_POST['username'];
if (isset($name)){
$data = "OK";
header('Content-Type: text/plain');
echo $data;
}
?>
Was mache ich falsch?
Sind Sie auf die URL veröffentlichen, die das PHP-Skript? Das Problem ist auf der Android-Seite. – mkaatman
@mkaatman Ja, die URL ist korrekt, weil ich den PHP-Fehler in der Antwort bekomme. – Hechi
versuchen Sie 'Anwendung/json;' in Java –