Запрос тела Android Volley POST получен ПУСТОЙ на сервере
Я использую следующий код для публикации объекта JSON на сервере PHP:
Map<String, String> paramsMap = new HashMap<String, String>();
paramsMap.put("tag", "jsonParams");
JSONObject jsonObject = new JSONObject(paramsMap);
Log.d("JSON", jsonObject.toString());
JsonObjectRequest jsonRequest = new JsonObjectRequest(Request.Method.POST, url, jsonObject,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.d("JSON RESPONSE", response.toString());
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.d("JSON ERROR", error.getMessage());
}
});
requestQ.add(jsonRequest);
и используя это, чтобы получить объект в php:
$body = '';
$handle = fopen('php://input','r');
while(!feof($handle)){
$body .= fread($handle,1024);
}
$logger->log("login request","request body: ".$body);
проблема в том, что $body всегда пусто, я использовал FIDDLER для проверки моего HTTP-запроса, и он там в виде необработанных данных, таких как: {"tag":"jsonParams"}, так что я тут испортил? спасибо заранее.
2 ответа
Не уверен, в чем была ваша проблема, но для будущих гуглеров:
Моя проблема заключалась в том, что я не читал с php://input
Полный код (рабочий):
Джава:
JSONObject jsonobj; // declared locally so that it destroys after serving its purpose
jsonobj = new JSONObject();
try {
// adding some keys
jsonobj.put("new key", Math.random());
jsonobj.put("weburl", "hashincludetechnology.com");
// lets add some headers (nested JSON object)
JSONObject header = new JSONObject();
header.put("devicemodel", android.os.Build.MODEL); // Device model
header.put("deviceVersion", android.os.Build.VERSION.RELEASE); // Device OS version
header.put("language", Locale.getDefault().getISO3Language()); // Language
jsonobj.put("header", header);
// Display the contents of the JSON objects
display.setText(jsonobj.toString(2));
} catch (JSONException ex) {
display.setText("Error Occurred while building JSON");
ex.printStackTrace();
}
JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.POST, URL, jsonobj, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
System.out.println("onResponse()");
try {
result.setText("Response: " + response.toString(2))
System.out.println("Response: " + response.toString(2));
} catch (JSONException e) {
display.setText("Error Occurred while building JSON");
e.printStackTrace();
}
//to make sure it works backwards as well
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
System.out.println("onErrorResponse()");
System.out.println(error.toString());
}
});
System.out.println("After the request is made");
// Add the request to the RequestQueue.
queue.add(jsObjRequest);
Разъяснение: display
а также result
два TextView
объекты, которые я использую для отображения данных на экране, и queue
очередь запросов Волли.
PHP:
$inp = json_decode(file_get_contents('php://input')); //$input now contains the jsonobj
echo json_encode(["foo"=>"bar","input"=>$inp]); //to make sure we received the json and to test the response handling
Ваш Android-монитор должен выводить sth. лайк:
{
"foo":"bar",
"input":{
"new key":0.8523024722406781,
"weburl":"hashincludetechnology.com",
"header": {
"devicemodel":"Android SDK built for x86",
"deviceVersion":"7.1",
"language":"eng"
}
}
}
Я знаю, что это старый вопрос, но для будущих читателей...
Я решил ту же проблему, используя StringRequest
вместо JsonObjectRequest
, Конструктор отличается очень незначительно, и вы можете легко проанализировать строковый ответ на JsonObject следующим образом:
JSONObject response = new JSONObject(responseString);