格森邮报方法

时间:2018-11-09 05:40:14

标签: android android-studio android-volley gson

如何将参数用于POST请求和GET响应?我有两个Model类。每个都有一个电话变量。如何发布而不会崩溃?如何在json中打印logcat文件?

依赖项:

implementation 'com.mcxiaoke.volley:library:1.0.19'
implementation 'com.google.code.gson:gson:2.8.5'

自定义Gson:

public class GsonRequest<T> extends Request<T> {
private Gson gson = new Gson();
private Class<T> clazz;
private Map<String, String> headers;
private Map<String, String> params;
private Listener<T> listener;


/**
 * Make a GET request and return a parsed object from JSON.
 *
 * @param url    URL of the request to make
 * @param clazz  Relevant class object, for Gson's reflection
 * @param params Map of request headers
 */
public GsonRequest(int method, String url, Class<T> clazz, Map<String, String> params, Listener<T> listener, ErrorListener errorListener) {
    super(method, url, errorListener);
    this.clazz = clazz;
    this.headers = null;
    this.params = params;
    this.listener = listener;
    gson = new Gson();
}

@Override
public Map<String, String> getHeaders() throws AuthFailureError {
    return headers != null ? headers : super.getHeaders();
}

@Override
protected Map<String, String> getParams() throws AuthFailureError {
    return params;
}

@Override
protected void deliverResponse(T response) {
    listener.onResponse(response);
}

@Override
protected Response<T> parseNetworkResponse(NetworkResponse response) {
    try {
        String json = new String(response.data,
                HttpHeaderParser.parseCharset(response.headers));
        return Response.success(
                gson.fromJson(json, clazz),
                HttpHeaderParser.parseCacheHeaders(response));
    } catch (UnsupportedEncodingException | JsonSyntaxException e) {
        return Response.error(new ParseError(e));
    }
}
}

请求:

 RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());

    GsonRequest<Model> gsonRequest = new GsonRequest<Model>(Request.Method.POST, url, Model.class, null, new Response.Listener<Model>() {

        @Override
        public void onResponse(Model response) {
            Toast.makeText(getApplicationContext(), "success" + " " + response, Toast.LENGTH_LONG).show();
            Log.d(TAG, response.toString());
        }
    }, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {

            textView.setText(error.toString());
            Toast.makeText(getApplicationContext(), "error" + " " + error, Toast.LENGTH_LONG).show();
            Log.d(TAG, error.toString());
        }
    });

    requestQueue.add(gsonRequest);
}

主要型号:

public class Model {
private Business business;

private Contacts contacts;

public Model(Business business, Contacts contacts) {
    this.business = business;
    this.contacts = contacts;
}

商业模式:

public class Business {

private String created_by;

private String business_name;

private String phone;

private String business_description;

private String address;

private String customer_name;

private String businessEmail;

private String business_type;

public Business(String created_by, String business_name, String phone, String business_description, String address,
                String customer_name, String businessEmail, String business_type) {

    this.created_by = created_by;
    this.business_name = business_name;
    this.phone = phone;
    this.business_description = business_description;
    this.address = address;
    this.customer_name = customer_name;
    this.businessEmail = businessEmail;
    this.business_type = business_type;
}

联系方式:

public class Contacts {
private String lastName;

private String phone;

private String email;

private String firstName;

public Contacts(String lastName, String phone, String email, String firstName) {
    this.lastName = lastName;
    this.phone = phone;
    this.email = email;
    this.firstName = firstName;
}

Json文件:

  { "business": { 
          "address": "xxx", 
          "business_description": "xx",
         "businessEmail": "xxx@gmail.com", 
         "business_name": "xxx", 
         "phone":"1234567890",
         "business_type": "xx",
         "created_by": "xxx",
         "customer_name": "xxx" 
         }, 
        "contacts": [ {  
              "email": "yyy@gmail.com",
              "firstName": "yyy", 
              "lastName": "yyy", "phone": "6544324569"  
        } ]
 }

1 个答案:

答案 0 :(得分:1)

我认为您已经解决了。不知道在哪里以及为什么很难将参数传递给请求。

根据这里发布的示例JSON文件,我建议对您的Model.java进行一些改动。

import java.util.List;
import java.util.ArrayList;

public class Model {

    private Business business;

    private List<Contacts> contacts = new ArrayList<>(); /* changes */

    public Model(Business business, List<Contacts> contacts) {
        this.business = business;
        this.contacts.addAll(contacts);  /* changes */
    }
}

“活动”或“片段”中的现在准备数据并将其传递给请求。

List<Contacts> contacts = new ArrayList<>();

Contacts con1 = new Contacts(/* required parameters */);

contacts.add(con1);

Contacts con2 = new Contacts(/* required parameters */);

contacts.add(con2);

// add as many as you want

Business business = new Business(/* required parameters */);

// add both parameters to Model class

Model data = new Model(business, contacts);

// and finally pass it to request parameter

RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());

GsonRequest<Model> gsonRequest = new GsonRequest<Model>(
        Request.Method.POST,
        url, 
        data, /* PLEASE NOTICE THE DIFFERENCE HERE: use data of type Model instead of Model.class */
        null, 
        new Response.Listener<Model>() {
            @Override
            public void onResponse(Model response) {
                Toast.makeText(getApplicationContext(), "success" + " " + response, Toast.LENGTH_LONG).show();
                Log.d(TAG, response.toString());
            }
        }, 
        new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

                textView.setText(error.toString());
                Toast.makeText(getApplicationContext(), "error" + " " + error, Toast.LENGTH_LONG).show();
                Log.d(TAG, error.toString());
            }
        }
);

requestQueue.add(gsonRequest);

在这里,您需要更改GsonRequest<Model>()构造函数的第3个参数。