gpt4 book ai didi

java - Android Volley 将 json 数据发布到服务器

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:53:15 26 4
gpt4 key购买 nike

我是 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

关于java - Android Volley 将 json 数据发布到服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44732699/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com