Android Volley - 无法使用 POST 执行 JSON 请求,得到空响应

Android Volley - can't do a JSON request with POST, getting empty response

我正在尝试使用 Volley 库向 php 服务器发出 json 请求,但由于某种原因,服务器没有收到我发送的 json 对象,并且它以空字符串响应。 这是我的代码

import android.content.Context;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response.Listener;
import com.android.volley.Response.ErrorListener;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;

public class MyVolley implements  Listener, ErrorListener {

    private static Context appContext;

    public MyVolley(Context context) {
        appContext = context;
    }

    public void stuff() throws JSONException {
        RequestQueue queue = Volley.newRequestQueue(appContext);
        JSONObject obj = new JSONObject();
        obj.put("param1", "assda");
        obj.put("param2", "fassfafsa");
        JsonObjectRequest stringRequest = new JsonObjectRequest(Request.Method.POST, "some url here", obj, this, this);
        queue.add(stringRequest);
    }

    @Override
    public void onResponse(Object response) {
        System.out.println(response);
    }

    @Override
    public void onErrorResponse(VolleyError error) {
        System.out.println(error);
    }
}

当它执行时,这就是服务器收到的内容

array (
  'Content-Type' => 'application/json; charset=utf-8',
  'User-Agent' => 'pointless info here',
  'Host' => 'some host here',
  'Connection' => 'Keep-Alive',
  'Accept-Encoding' => 'gzip',
  'Content-Length' => '107',
) array (
) array (
)

为什么会这样?

确保这不是服务器端错误(例如使用 Postman 尝试您的服务)。

我个人前段时间遇到过同样的问题,将 JsonObjectRequest 更改为 StringRequest 解决了我的问题。

看看这个 link:

现在我使用 Retrofit2 而不是 Volley...可能是一种选择。 快乐编码

不确定你的问题是什么,但对于未来的谷歌员工:

我的问题是我试图阅读表格 $_POST 而不是 php://input

完整代码(有效):

Java:

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);

澄清:displayresult是我用来在屏幕上显示数据的两个TextView对象,queue是Volley的请求队列。

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 监视器应该输出某事。喜欢 :

{
    "foo":"bar",
    "input":{
        "new key":0.8523024722406781,
        "weburl":"hashincludetechnology.com",
        "header": {
            "devicemodel":"Android SDK built for x86",
            "deviceVersion":"7.1",
            "language":"eng"
        }
    }
}