Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

volley multpart post 。response失败,提示没有接受到params参数。但getbody等断点调试,params都有数据的。不知道问题出在哪了? #113

Closed
ayyb1988 opened this issue Mar 29, 2015 · 1 comment

Comments

@ayyb1988
Copy link

post 参数有两种类型,一直是普通的string。一种是zip文件。
自定义了MultipartGsonRequest ,如下。
public class MultipartGsonRequest extends Request {
private static final String TAG = "MultipartGsonRequest";
MultipartEntityBuilder entity = MultipartEntityBuilder.create();

private final Class mClass;
private Response.Listener mListener;
private final Gson gson;
private final File mFilePart;
private final Map<String, String> mStringPart;
private static final String FILE_PART_NAME = "img";
private HttpEntity httpentity;

public MultipartGsonRequest(String url, Class clazz,File file,
                            Map<String, String> mStringPart,
                            Response.Listener listener,
                            Response.ErrorListener errorListener) {
    super(Request.Method.POST, url, errorListener);
    mClass = clazz;
    mListener = listener;
    gson = new Gson();
    mFilePart = file;
    this.mStringPart = mStringPart;
    entity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

// try {
// entity.setCharset(CharsetUtils.get("UTF-8"));
// } catch (UnsupportedEncodingException e) {
// e.printStackTrace();
// }
buildMultipartEntity();
}

public void addStringBody(String param, String value) {
    mStringPart.put(param, value);
}

private void buildMultipartEntity() {
    entity.addPart(FILE_PART_NAME, new FileBody(mFilePart, ContentType.create("application/zip"), mFilePart.getName()));
    for (Map.Entry<String, String> entry : mStringPart.entrySet()) {
        entity.addTextBody(entry.getKey(), entry.getValue(),ContentType.TEXT_PLAIN.withCharset("UTF-8"));
    }
}

@Override
public String getBodyContentType() {
    return httpentity.getContentType().getValue();
}

@Override
public byte[] getBody() throws AuthFailureError {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    try {
        httpentity = entity.build();
        httpentity.writeTo(bos);
    } catch (IOException e) {
        VolleyLog.e("IOException writing to ByteArrayOutputStream");
    }
    return bos.toByteArray();
}

@Override
protected Response parseNetworkResponse(NetworkResponse response) {
    String json;
    try {
        json = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
    } catch (UnsupportedEncodingException e) {
        Log.e(TAG, String.format("Encoding problem parsing API response. NetworkResponse:%s", response.toString()), e);
        return Response.error(new ParseError(e));
    }
    try {
        return Response.success(gson.fromJson(json, mClass), HttpHeaderParser.parseCacheHeaders(response));
    } catch (JsonSyntaxException e) {
        Log.e(TAG, String.format("Couldn't API parse JSON response. NetworkResponse:%s", response.toString()), e);
        Log.e(TAG, String.format("Couldn't API parse JSON response. Json dump: %s", json));
        return Response.error(new ParseError(e));
    }
}

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

}

调用multpart请求。
for (int i = 0; i < Bimp.tempSelectBitmap.size(); i++) {
File f = new File(Bimp.tempSelectBitmap.get(i).imagePath);
resFileList.add(f);
}
String url = ApiUrl.JoinActivityCreate;
Map<String, File> files = new HashMap<String, File>();
if (resFileList != null && resFileList.size() > 0 && zipFile != null) {
try {
ZipUtils.zipFiles(resFileList, zipFile);
} catch (IOException e) {
e.printStackTrace();
}
}

    Map<String, String> params = new HashMap<String, String>();

    params.put("Cer", GlobalData.curUser.getCryptoCer());
    params.put("Title", etActivityTitle.getText().toString());
    params.put("EndTime", btActivityEndTime.getText().toString());
    params.put("Address", etActivityAddress.getText().toString());
    params.put("Latitude", String.valueOf(latitude));
    params.put("Longitude", String.valueOf(longitude));
    params.put("Content", etActivityIntroduction.getText().toString());
    params.put("MaxJoinCount", String.valueOf(etMaxJoinCount.getText().toString()));
    StringBuffer catestr = new StringBuffer();
    for (int i = 0; i < cates.size(); i++) {
        if (i == cates.size() - 1) {
            catestr.append(cates.get(i));
        } else {
            catestr.append(cates.get(i)).append(",");
        }
    }
    params.put("Cates", String.valueOf(catestr));
    StringBuffer infoitemstr = new StringBuffer();
    for (int i = 0; i < joinInputItems.size(); i++) {
        if (i == joinInputItems.size() - 1) {
            infoitemstr.append(joinInputItems.get(i).getName());
        } else {
            infoitemstr.append(joinInputItems.get(i).getName()).append(",");
        }
    }
    params.put("InfoItemIds", String.valueOf(infoitemstr));
    params.put("App", String.valueOf(GlobalData.app));
    params.put("V", String.valueOf(Util.getVersionInfo(this)));
    params.put("Serial", Util.getIMEI(this));

    MultipartGsonRequest<JoinActivity> request = new MultipartGsonRequest<JoinActivity>(url, JoinActivity.class,
            zipFile, params, new Response.Listener<JoinActivity>() {
        @Override
        public void onResponse(JoinActivity joinActivity) {
            if (joinActivity.getCode() == 0) {
                MyToast.makeText(PublishActivities.this, "发布成功", Toast.LENGTH_SHORT);
            } else {
                MyToast.makeText(PublishActivities.this, joinActivity.getErrMsg(), Toast.LENGTH_LONG);
            }

        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError volleyError) {
            MyToast.makeText(PublishActivities.this, volleyError.toString(), Toast.LENGTH_LONG);
        }
    }) {

        @Override
        public String getBodyContentType() {
            return "multipart/form-data";
        }
    };


    request.setRetryPolicy(new DefaultRetryPolicy(10000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

// MySingleton.getInstance(this).addHttpStackToRequestQueue(request);
MySingleton.getInstance(this).addToRequestQueue(request);
}

其中 MySingleton.getInstance(this).addToRequestQueue(request) 如下。
public RequestQueue getRequestQueue() {
if (requestQueue == null) {
requestQueue = Volley.newRequestQueue(mCtx.getApplicationContext());
}
return requestQueue;
}

public <T> void addToRequestQueue(Request<T> req) {
    getRequestQueue().add(req);
}
@ayyb1988
Copy link
Author

ayyb1988 commented Apr 5, 2015

已解决。

@ayyb1988 ayyb1988 closed this as completed Apr 5, 2015
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant