繁体   English   中英

如何在Android中使用Volley发送Json发布请求?

[英]How to send a Json post request using volley in android?

我的服务器采用JSON格式的Post请求,因此我创建了POJO类,在其中为它设置了数据并使用GSON(toJson()方法)转换为JSON字符串。

我在应用程序中使用Volley库。如何使用Volley发送发帖请求? 我尝试了以下代码:

 Entity object = new Entity();
                        LinkedHashMap<String, Object> properties = new LinkedHashMap<String, Object>(7);
                        properties.put("email",email);
                        properties.put("phone",phone);
                        properties.put("passwd",password);
                        properties.put("name",username);
                        properties.put("crycode","IN");
                        object.setType(EntityType.USER);
                        object.setProperties(properties);
                        Gson gson = new Gson();


                        Map<String,String> headers = new HashMap<String, String>(1);
                        headers.put("Content-Type", "application/json");

                        String url = "my server URL";
 GsonRequest<RegisterResponse> myReq = new GsonRequest<RegisterResponse>(
                                com.android.volley.Request.Method.POST,
                                url,
                                RegisterResponse.class,
                                gson.toJson(object),headers,
                                createMyReqSuccessListener(),
                                createMyReqErrorListener());

                    AppController.getInstance().addToRequestQueue(myReq);

当我的服务器接受JSON格式的请求时,我是否需要再次将JSON字符串转换为JSON对象,或者我转换的字符串就足够了? 以及如何立即发送请求?

请帮助我解决这个问题。

您的POJO类应如下所示:

    public class Entity {
    private String email;
    private String phone;
    private String passwd;
    private String name;
    private String crycode;

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public String getPasswd() {
        return passwd;
    }

    public void setPasswd(String passwd) {
        this.passwd = passwd;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getCrycode() {
        return crycode;
    }

    public void setCrycode(String crycode) {
        this.crycode = crycode;
    }
}

请看到我忽略了userType,您也可以添加它。 然后最终将其提供给Gson,它将将该类转换为JSON String。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM