【问题标题】:Android: How to check if succesfully sent JSON data to server using volley?Android:如何使用 volley 检查是否成功将 JSON 数据发送到服务器?
【发布时间】:2017-04-25 12:23:18
【问题描述】:

我想将 JSON 数据从我的应用程序发送到服务器。我正在使用凌空库。我在这里查看了这个问题Volley send JSONObject to server with POST method。我设法从服务器获得响应,这是“好的”,但我在尝试发送数据时是否遗漏了某些内容,或者我是否已成功将其发送到服务器?

我的数据存储在JSONObject d 中,看起来像

{   "temp_mC":0,
    "humidity_ppm":28430,
    "pressure_Pa":101242,
    "temp2_mC":32937,
    "co_mV":238,
    "no2_mV":1812,
    "noise_dB":79,      
}

我调用的发布数据的方法

  public void postData(JSONObject d) {
    try {

       final String requestBody = d.toString();

        StringRequest stringRequest = new StringRequest(1, "http:.....", new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                Log.d("Response",response);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
               Log.e("Error:",error.toString());
            }
        }) {
            @Override
            public String getBodyContentType() {
                return String.format("application/json; charset=utf-8");
            }

            @Override
            public byte[] getBody() throws AuthFailureError {
                try {
                    return requestBody == null ? null : requestBody.getBytes("utf-8");
                } catch (UnsupportedEncodingException uee) {
                    VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s",
                            requestBody, "utf-8");
                    return null;
                }
            }
        };
         MySingleton.getInstance(this).addToRequestQueue(stringRequest);

    } catch (Exception e) {
        e.printStackTrace();
    }


}

还有来自示例代码的 MySingleton 类

 public class MySingleton {
private static MySingleton mInstance;
private RequestQueue mRequestQueue;
private ImageLoader mImageLoader;
private static Context mCtx;

private MySingleton(Context context) {
    mCtx = context;
    mRequestQueue = getRequestQueue();

    mImageLoader = new ImageLoader(mRequestQueue,
            new ImageLoader.ImageCache() {
                private final LruCache<String, Bitmap>
                        cache = new LruCache<String, Bitmap>(20);

                @Override
                public Bitmap getBitmap(String url) {
                    return cache.get(url);
                }

                @Override
                public void putBitmap(String url, Bitmap bitmap) {
                    cache.put(url, bitmap);
                }
            });
}

public static synchronized MySingleton getInstance(Context context) {
    if (mInstance == null) {
        mInstance = new MySingleton(context);
    }
    return mInstance;
}

public RequestQueue getRequestQueue() {
    if (mRequestQueue == null) {
        // getApplicationContext() is key, it keeps you from leaking the
        // Activity or BroadcastReceiver if someone passes one in.
        mRequestQueue = Volley.newRequestQueue(mCtx.getApplicationContext());
    }
    return mRequestQueue;
}

public <T> void addToRequestQueue(Request<T> req) {
    getRequestQueue().add(req);
}

public ImageLoader getImageLoader() {
    return mImageLoader;
}
}

【问题讨论】:

    标签: java android json post android-volley


    【解决方案1】:

    如果您从服务器获得 OK,那么最合乎逻辑的事情就是数据已发送。我们不知道您使用的是什么服务器,以及发送错误数据时服务器返回给客户端的内容。

    当您发送错误数据时,您的服务器可能也会发送 OK 状态 (200),您应该检查您的服务器是否一切正常,从 volley 的响应来看一切正常。

    【讨论】:

    • 我尝试将其发送到此服务器httpbin.org/post,它与帖子数据相呼应。服务器响应确实是我的数据,这意味着它可以在我这边工作,对吗?
    【解决方案2】:

    在 onResponse 中成功完成您的请求后,检查如下状态代码,如果状态代码为 200,则表示您的请求已成功执行

    private NetworkResponse networkResponse;
    @Override
    protected Response<String> parseNetworkResponse(NetworkResponse response) {
        networkResponse = response;
        return super.parseNetworkResponse(response);
    
    }
    
     @Override
            public void onResponse(String response) {
                if(networkResponse.statusCode==200)
                 {
                  // then perform your task
                    Log.d("Response",response);
                 }
            }
    

    【讨论】:

    • 您好,谢谢您的回答。我应该在哪里添加 parseNetworkResponse 方法?
    • 在您使用扩展字符串请求的同一类上
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-05
    • 1970-01-01
    • 2014-11-06
    • 2018-02-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多