在Volley中转换Http Post请求

时间:2016-01-19 04:59:52

标签: android android-volley

我想使用Volley发布反馈数据。

我获得了使用Http Request的参考代码,但我无法在Http Post request调用中转换volley

参考代码:

 FeedBack feedBack = new FeedBack();
        feedBack.message = edtMessage.getText().toString().trim();
        feedBack.name = edtName.getText().toString().trim();
        feedBack.stars = star;
        if (dialog != null) dialog.show();
        HttpRequest http = new HttpRequest(getMainActivity(), Url, BaseRestClient.RequestMethod.POST, BaseModel.class, this);
        http.addParam("data", new Gson().toJson(feedBack));
        http.executeAsync();
    }
}

@Override
public void onSuccess(BaseModel baseModel) {
    if (dialog != null && dialog.isShowing()) dialog.dismiss();
    if (baseModel != null) {
        Log.i("output", "onSuccess> " + new Gson().toJson(baseModel));
    }
}

@Override
public void onHttpError(ResponseStatus responseStatus) {
    if (dialog != null && dialog.isShowing()) dialog.dismiss();
    if (responseStatus != null)
        Log.i("output", "onHttpError> " + new Gson().toJson(responseStatus));
}

我尝试使用StringRequest,但无法按上述方式添加BaseModel

StringRequest stringRequest = new StringRequest(Request.Method.POST,
                Url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        if (dialog != null && dialog.isShowing()) dialog.dismiss();

                        Log.d("Response", response.toString());
                        Toast.makeText(getActivity(), "" + response.toString(), Toast.LENGTH_SHORT).show();
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        if (dialog != null && dialog.isShowing()) dialog.dismiss();
                        Log.d("Error.Response", "" + error);
                    }
                }
        ) {
            @Override
            protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<String, String>();
                params.put("data", new Gson().toJson(feedBack));
                return params;
            }
        };

我需要String,而不是BaseModel类型。

请建议我该怎么做?

谢谢。

1 个答案:

答案 0 :(得分:0)

您可以参考以下示例代码:

这里,我的POJO类是FileInfo,例如:

public class FileInfo {
    public String Type;
    public long Size;
    public String Modified;
    public byte[] Data;

    public FileInfo() {

    }
}

然后,按以下方式创建FileRequest.java

public class FileRequest extends Request<FileInfo> {
    private final String mRequestBody;
    private final Response.Listener<FileInfo> mListener;
    private final Response.ErrorListener mErrorListener;

    private static final String PROTOCOL_CHARSET = "utf-8";
    private static final String PROTOCOL_CONTENT_TYPE = String.format("application/json; charset=%s", PROTOCOL_CHARSET);

    public FileRequest(int method, String url, Response.Listener<FileInfo> listener, Response.ErrorListener errorListener) {
        super(method, url, errorListener);
        this.mRequestBody = null;
        this.mListener = listener;
        this.mErrorListener = errorListener;
    }

    public FileRequest(String url, String requestBody, Response.Listener<FileInfo> listener, Response.ErrorListener errorListener) {
        super(requestBody == null ? Method.GET : Method.POST, url, errorListener);
        this.mRequestBody = requestBody;
        this.mListener = listener;
        this.mErrorListener = errorListener;
    }

    public FileRequest(int method, String url, String requestBody, Response.Listener<FileInfo> listener, Response.ErrorListener errorListener) {
        super(method, url, errorListener);
        this.mRequestBody = requestBody;
        this.mListener = listener;
        this.mErrorListener = errorListener;
    }

    @Override
    protected Response<FileInfo> parseNetworkResponse(NetworkResponse response) {
        try {
            FileInfo fileInfo = new FileInfo();
            fileInfo.Size = Long.valueOf(response.headers.get("Content-Length"));
            fileInfo.Type = response.headers.get("Content-Type");
            fileInfo.Modified = response.headers.get("Last-Modified");
            fileInfo.Data = response.data;
            return Response.success(fileInfo, HttpHeaderParser.parseCacheHeaders(response));
        } catch (Exception e) {
            return Response.error(new ParseError(e));
        }
    }

    @Override
    protected void deliverResponse(FileInfo response) {
        mListener.onResponse(response);
    }

    @Override
    protected VolleyError parseNetworkError(VolleyError volleyError) {
        return super.parseNetworkError(volleyError);
    }

    @Override
    public void deliverError(VolleyError error) {
        mErrorListener.onErrorResponse(error);
    }

    @Override
    public String getBodyContentType() {
        return PROTOCOL_CONTENT_TYPE;
    }

    @Override
    public byte[] getBody() throws AuthFailureError {
        try {
            return mRequestBody == null ? null : mRequestBody.getBytes(PROTOCOL_CHARSET);
        } catch (UnsupportedEncodingException uee) {
            VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s",
                mRequestBody, PROTOCOL_CHARSET);
            return null;
        }
    }
}

然后,您可以致电:

        FileRequest fileRequest = new FileRequest(method, url, requestBody, new Response.Listener<FileInfo>() {
            @Override
            public void onResponse(FileInfo response) {
                // do something...
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                // do something...
            }
        });