我想使用带有 volley 库的 POST 方法创建一个 JsonObjectRequest,以便我可以将我的数据保存在服务器上。
同样,我有一个 jsonObject 的 API,如下所示:
{"settings":{"notification":30,"time":4}}
相同的java代码如下;
public void sendrequest(String urlset)
{
RequestQueue requestQueue1=Volley.newRequestQueue(this);
JSONObject json=new JSONObject();
JsonObjectRequest jsonObjectRequest1=new JsonObjectRequest(Request.Method.POST, urlset, json, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
//code for getting some response from the method
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
//code in order to check the error
}
});
}
如何做到这一点,以便我能够使用上面的代码将我的数据发布到服务器上(供参考)。
提前致谢。
经过几次尝试后,我尝试这样做:
public void sendrequest(String urlset)
{
RequestQueue requestQueue1=Volley.newRequestQueue(this);
String a,b;
SharedPreferences sharedPreferences1=getSharedPreferences("MyPreferences",MODE_PRIVATE);
a=sharedPreferences1.getString("list_preference_1","");
b=sharedPreferences1.getString("list_preference_2","");
//a=sharedPreferences1.getInt("list_preference_1", 1);
//b=sharedPreferences1.getInt("list_preference_2", 1);
JSONObject json=new JSONObject();
try {
//JSONObject ob=json.getJSONObject("settings");
json.put("notification",Integer.parseInt(a));
json.put("time",Integer.parseInt(b));
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(this, "Error 1", Toast.LENGTH_SHORT).show();
}
JSONObject jsonfinal=new JSONObject();
try {
jsonfinal.put("settings",json);
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(this, "Error 2", Toast.LENGTH_SHORT).show();
}
JsonObjectRequest jsonObjectRequest1=new JsonObjectRequest(Request.Method.POST, urlset, jsonfinal, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Toast.makeText(SettingsActivity.this, "Changes made to server", Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(SettingsActivity.this, "Check internet connectivity", Toast.LENGTH_SHORT).show();
}
});
requestQueue1.add(jsonObjectRequest1);
}
但是现在我的应用程序正在崩溃。有人可以帮我解决这个问题吗?