我正在尝试使用 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 解决了我的问题。
看看这个链接:https : //stackoverflow.com/a/31613565/7871886
现在我使用 Retrofit2 而不是 Volley ......可能是一个选择。快乐编码
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句