我是 Java 新手。我想将 post json 数据发送到网络服务器。
下面给出了我的 Volley 帖子。
public void postData(String url,JSONObject data,final VolleyCallback mResultCallback){
RequestQueue requstQueue = Volley.newRequestQueue(mContext);
JsonObjectRequest jsonobj = new JsonObjectRequest(Request.Method.POST, url,null,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
if(mResultCallback != null){
mResultCallback.notifySuccess(response);
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
if(mResultCallback != null){
mResultCallback.notifyError(error);
}
}
}
){
//here I want to post data to sever
};
requstQueue.add(jsonobj);
}
这是我的 MainActivity 代码
JSONObject data = null;
try {
String datas = "{'email': email,'password': password}";
data = new JSONObject(datas);
}catch (JSONException e){
e.printStackTrace();
}
String url = "http://example.com";
我想将 JSON 数据发布到我的 PostData 方法。
如何将此json数据发布到我的服务器?
最佳答案
public void postData(String url,Hashmap data,final VolleyCallback mResultCallback){
RequestQueue requstQueue = Volley.newRequestQueue(mContext);
JsonObjectRequest jsonobj = new JsonObjectRequest(Request.Method.POST, url,new JSONObject(data),
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
if(mResultCallback != null){
mResultCallback.notifySuccess(response);
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
if(mResultCallback != null){
mResultCallback.notifyError(error);
}
}
}
){
//here I want to post data to sever
};
requstQueue.add(jsonobj);
}
现在,从你的 mainActiviy 类
Hashmap data = new HashMap();
data.put("email","email");
data.put("password","password");
String url = "http://example.com";
//now you can just call the method, I have rectified your string to hashmap,
postData(url,data,new mResultCallb..... //rest of your code