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

ali*_*ien 3 java webserver android json android-volley

我是Java新手.我想将post json数据发送到webserver.我的排球发布如下.

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);

}
Run Code Online (Sandbox Code Playgroud)

这是我的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";
Run Code Online (Sandbox Code Playgroud)

我想将JSON数据发布到PostData方法.如何将此json数据发布到我的服务器?

Ran*_*jan 6

    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);

    }
Run Code Online (Sandbox Code Playgroud)

现在,来自你的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
Run Code Online (Sandbox Code Playgroud)