【发布时间】: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