Android Volley-无法通过POST执行JSON请求,得到空响应 [英] Android Volley - can't do a JSON request with POST, getting empty response

查看:162
本文介绍了Android Volley-无法通过POST执行JSON请求,得到空响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to make a json request using Volley library to a php server, but for some reason the server does not receive the json object I am sending, and it responds with empty string. Here is my code

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

执行时,这就是服务器收到的信息

And when it executes, this is what the server receives

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尝试服务).

Make sure it's not a server side error (try your service using Postman for instance).

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

I personally faced the same issue some time ago, changing JsonObjectRequest to StringRequest fixed my problem.

看看这个链接: https://stackoverflow.com/a/31613565/7871886

现在,我使用Retrofit2而不是Volley ...可以选择. 编码愉快

Now I use Retrofit2 instead of Volley... Could be an option. Happy coding

这篇关于Android Volley-无法通过POST执行JSON请求,得到空响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆