Volley Post请求在onResponse中没有返回任何响应

时间:2017-07-26 11:49:59

标签: java android json post android-volley

所以我想打印响应的结果,然后使用gson为模型生成数据,但响应永远不会返回onResponse被调用。!

如果你注意到Logcat,onResponse里面的log.i没有显示..!?但是在使用此请求的Activity的onSuccess中,它会正常显示日志,但如果日志包含响应对象,则它不显示哪个非常奇怪且没有任何意义..!

logcat的

I/getUrl:: http://1925.232.55/login.php
I/getParams:: {username =samy, password=123456}
D/libc: [NET] android_getaddrinfofornetcontext+,hn 20(0x6),sn(),hints(known),family 0,flags 1024, proc=com...
D/libc: [NET] android_getaddrinfo_proxy get netid:0
D/libc: [NET] android_getaddrinfo_proxy-, success
I/onSuccess:: check /* this log inside the Activity which uses this request */
  

我尝试使用PostMan使用相同的url和params测试请求   它正常返回json响应..?

邮差回应

{
    "status": "success",
    "user_id": "10",
    "user_name": "samy",
    "full_name": "samy samy",
    "picture": "st_pictures/IMG_085207.jpg",
    "level": "1",
    "school": "NY School",
    "city": "NY",
    "class": "6",
    "age": "22",
    "teacher": "2",
    "token": "f808e758sdfsdfsf162dbdfcf88e3dc8a96"
}

请求代码

 final RequestQueue queue = Volley.newRequestQueue(context);

      final StringRequest sr = new StringRequest(Request.Method.POST, getLoginURL(), new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
          Log.i("onResponse: ", response + "");
      requestResult.onSuccess(response);


      }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
      requestResult.onFail(error);

           VolleyLog.e("Error: ", error.getMessage());
          error.printStackTrace();
        }
      })
      {
        @Override
        protected Map<String, String> getParams() {
          Map<String, String> params = new HashMap<String, String>();
          params.put("username ", un);
          params.put("password", pass);
          Log.i( "getParams: ", params.toString());
          return params;
        }

        @Override
        public byte[] getBody() throws AuthFailureError {
          Log.i( "getUrl: ",getUrl());
          return super.getBody();

        }
      }
      ;

      queue.add(sr);

更新#1

网址http://clients.intertech.ps/raz/std.php

 E/Volley: [1] 2.onErrorResponse: Error: 
 W/System.err: com.android.volley.ParseError: org.json.JSONException: End of input at character 0 of 
 W/System.err:     at com.android.volley.toolbox.JsonObjectRequest.parseNetworkResponse(JsonObjectRequest.java:73)
 W/System.err:     at com.android.volley.NetworkDispatcher.run(NetworkDispatcher.java:123)
 W/System.err: Caused by: org.json.JSONException: End of input at character 0 of 
 W/System.err:     at org.json.JSONTokener.syntaxError(JSONTokener.java:449)
 W/System.err:     at org.json.JSONTokener.nextValue(JSONTokener.java:97)
 W/System.err:     at org.json.JSONObject.<init>(JSONObject.java:156)
 W/System.err:     at org.json.JSONObject.<init>(JSONObject.java:173)
W/System.err:     at com.android.volley.toolbox.JsonObjectRequest.parseNetworkResponse(JsonObjectRequest.java:68)
 W/System.err:  ... 1 more

3 个答案:

答案 0 :(得分:2)

这个问题是很久以前问的,但是我有同样的问题,几个小时后我就可以与Volley一起使用

使用StringRequest代替JsonObjectRequest,由于任何原因,我在JOR上遇到了很多问题,并且使用了@Oussema ArouagetHeaders函数

final Response.Listener<String> responseListener = new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            Log.d("RESPONSE", String.valueOf(response));
        }
    };

final Response.ErrorListener errorListener = new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

            //Handle your errors
        }
    };

StringRequest request = new StringRequest(Request.Method.POST, url,
            responseListener, errorListener) {
        @Override
        protected Map<String, String> getParams() {
            Map<String, String> params = new HashMap<>();
            //Put your params for post
            return params;
        }

        @Override
        public Map<String, String> getHeaders() {
            Map<String,String> params = new HashMap<>();
            params.put("Content-Type","application/x-www-form-urlencoded"); //-> this is the key
            return params;
        }
    };

..,您将从onResponse

中的服务器获取json响应

答案 1 :(得分:0)

它不是StringRequest您需要使用JsonObjectRequest,因为您的回复始于{

JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.GET,
                url, null,
                new Response.Listener<JSONObject>() {

                    @Override
                    public void onResponse(JSONObject response) {
                        Log.d(TAG, response.toString());
                       requestResult.onSuccess(response);
                    }
                }, new Response.ErrorListener() {

                    @Override
                    public void onErrorResponse(VolleyError error) {
                        VolleyLog.d(TAG, "Error: " + error.getMessage());
                        requestResult.onFail(error);
                    }
                });

尝试添加getParams

@Override
public Map<String, String> getHeaders() throws AuthFailureError {
    Map<String,String> params = new HashMap<String, String>();
    params.put("Content-Type","application/x-www-form-urlencoded");
    return params;
}

[更新]:

我不知道为什么凌空不起作用但我改为ion link并且它有效:

Ion.with(this)
                .load("http://clients.intertech.ps/raz/std.php")
                .setBodyParameter("username", "layal")
                .setBodyParameter("password", "123456")
                .asJsonObject()
                .setCallback(new FutureCallback<JsonObject>() {
                    @Override
                    public void onCompleted(Exception e, JsonObject jsonObject) {
                        Log.e("TAG", "onCompleted: " + jsonObject.toString());
                    }
                });

答案 2 :(得分:0)

您必须使用function mapNonNull(arr, cb) { return arr.reduce(function (accumulator, value, index, arr) { var result = cb.call(null, value, index, arr); if (result != null) { accumulator.push(result); } return accumulator; }, []); } var result = mapNonNull(["a", "b", "c"], function (value) { return value === "b" ? null : value; // exclude "b" }); console.log(result); // ["a", "c"],如下所示:

JsonObjectRequest