我想從我的應用程序發送JSON數據到服務器。我正在使用排球庫。我在這裏看到這個問題Volley send JSONObject to server with POST method。我設法從服務器獲得響應,這是「正常」,但是當我試圖發送數據或者我已經成功將它發送到服務器時,我錯過了什麼?Android:如何檢查是否使用volley將JSON數據成功發送到服務器?
我的數據被存儲在內部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;
}
}
謝謝你的答案。 – user7919140
我試着將它發送到這個服務器http://httpbin.org/post,它迴應了發佈數據。服務器的響應確實是我的數據,這意味着它在我的工作,對不對? – user7919140
是的,聽起來像你的代碼是正確的 – Denny