简体   繁体   中英

Android: How to check if succesfully sent JSON data to server using volley?

I want to send JSON data from my application to a server. I am using volley library. I looked at this question here Volley send JSONObject to server with POST method . I manage to get the response from the server, which is "OK" but am I missing something when trying to send the data or have I successfully sent it to the server?

My data is stored inside JSONObject d and looks like

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

The method which I call to post data

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


}

And MySingleton class which is from sample code

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

If you got OK from the server then most logical thing to think is that the data has been sent. We don't know what server you use and what the server returns to the client when faulty data gets sent.

Maybe your server also sends OK status (200) when you sent wrong data, you should check your server if everything went ok, from the response in volley everything seems fine.

After successfully completion of your request inside onResponse check for status code like below if status code is 200 its mean your request executed successfully

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM