如何使用Volley将JSON对象发送到服务器
问题描述:
我从服务器上使用Volley Library获取JSON数据,但现在需要将JSON发送到服务器。但我不知道如何发回JSONArray或JSONObject。如何使用Volley将JSON对象发送到服务器
我用下一个例子检索数据。
JsonArrayRequest program_from_event = new JsonArrayRequest(URL, new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
if(response.length() > 0){
for(int i = 0; i < response.length(); i++){
try {
JSONObject input = response.getJSONObject(i);
String name = input.getString("name");
String work_area = input.getString("work_area");
String email = input.getString("email");
String phone = input.getString("phone");
String avatar = input.getString("avatar");
String description = input.getString("description");
int id = input.getInt("id");
...
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
}, new Response.ErrorListener(){
@Override
public void onErrorResponse(VolleyError error) {
NetworkResponse nr = error.networkResponse;
if(nr != null && nr.statusCode == HttpStatus.SC_UNAUTHORIZED){
Log.i("ERROR", "ERROR");
}
}
});
volley_queue.add(program_from_event);
}
我该怎么办send方法?谢谢。
答
protected void callWebService(final User user) {
pd = ProgressDialog.show(activity, "Please Wait...", "Please Wait...");
RequestQueue queue = Volley.newRequestQueue(activity);
JsonObjectRequest jsObjRequest = new JsonObjectRequest(
Request.Method.POST,url,
createUserMapperObejct(user),
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
pd.dismiss();
Log.v("reponse", "" + response);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
});
queue.add(jsObjRequest);
}
public static JSONObject createUserMapperObejct(User user)
{
JSONObject request=new JSONObject();
try {
request.put(StringConstant.USERNAME, user.getUserName());
request.put(StringConstant.PASSWORD, user.getPassword());
request.put(StringConstant.CONFIRMPASSWORD, user.getPassword());
request.put(StringConstant.EMAILID, user.getEmailId());
request.put(StringConstant.CONTACTNO, user.getMobileNo());
} catch (JSONException e) {
e.printStackTrace();
}
return request;
}
+0
谢谢,我会测试它。 – MAOL 2014-09-12 10:31:44
+0
工作很好..谢谢 – 2015-03-02 08:07:35
检查:http://www.androidhive.info/2014/05/android-working-with-volley-library-1/ – 2014-09-12 10:27:24