本文介绍了如何在Android中发送multipart请求与排球的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些code到与Android凌空发送多部分请求。但是,当我尝试运行code,呈现BasicNetwork.performRequest:意外的响应code 401错误。

希望,有人能帮助我。谢谢你。

这我Multipartrequest。

 公共类MultipartRequest扩展请求<串GT; {
  MultipartEntityBuilder实体= MultipartEntityBuilder.create();
  HttpEntity httpentity;
  私人字符串FILE_PART_NAME =上载;  私人最终Response.Listener<串GT; mListener;
  私人最终文件mFilePart;
  私人最终地图<字符串,字符串> mStringPart;公共MultipartRequest(字符串URL,Response.ErrorListener errorListener,
                        Response.Listener<串GT;监听器,文件档案,
                        长度长,地图<字符串,字符串> mStringPart,HashMap的<字符串,字符串>头,HashMap的<字符串,字符串> PARAMS,对象o){
    超(Method.POST,网址,errorListener);    this.mListener =侦听器;
    this.mFilePart =文件;
    this.mStringPart = mStringPart;    entity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    尝试{
        entity.setCharset(CharsetUtils.get(UTF-8));
    }赶上(UnsupportedEncodingException五){
        e.printStackTrace();
    }
    buildMultipartEntity();
    httpentity = entity.build();
}私人无效buildMultipartEntity(){
    entity.addPart(FILE_PART_NAME,新FileBody(mFilePart,ContentType.create(图像/ JPEG),mFilePart.getName()));
    如果(mStringPart!= NULL){
        对于(Map.Entry的<字符串,字符串>项:mStr​​ingPart.entrySet()){
            entity.addTextBody(entry.getKey(),entry.getValue());
        }
    }
}@覆盖
公共字符串getBodyContentType(){
    返回httpentity.getContentType()的getValue()。
}@覆盖
公众的byte [] getBody()抛出AuthFailureError {    ByteArrayOutputStream BOS =新ByteArrayOutputStream();
    尝试
    {
        httpentity.writeTo(BOS);
    }
    赶上(IOException异常E)
    {
        VolleyLog.e(IOException异常写入ByteArrayOutputStream);
    }
    返回bos.toByteArray();
}@覆盖
受保护的响应<串GT; parseNetworkResponse(NetworkResponse响应){    尝试{
        的System.out.println(网络响应+新的String(response.data,UTF-8));
        返回Response.success(新的String(response.data,UTF-8),
                getCacheEntry());
    }赶上(UnsupportedEncodingException五){
        e.printStackTrace();
        返回Response.success(新的String(response.data),getCacheEntry());
    }
}@覆盖
保护无效deliverResponse(字符串响应){
    mListener.onResponse(响应);
}
}

和我这样调用多部分请求。

 私人无效上传(){
    HashMap的<字符串,字符串>标题=新的HashMap<字符串,字符串>();
    串凭证= AppConfig.USER_API +:+ AppConfig.PASSWORD_API;
    字符串AUTH =基本
            + Base64.en codeToString(credentials.getBytes()
            Base64.NO_WRAP);
    headers.put(授权,验证);    文件的资源文件=新的文件(文件路径);    HashMap的<字符串,字符串> PARAMS =新的HashMap<字符串,字符串>();
    params.put(递减,OK);    MultipartRequest multipartRequest =新MultipartRequest(AppConfig.URL_REPORT,            新Response.ErrorListener(){
                @覆盖
                公共无效onErrorResponse(VolleyError错误){
                    Log.e(TAG,失败:+ error.getMessage());
                    Toast.makeText(getApplicationContext(),
                            error.getMessage(),Toast.LENGTH_LONG).show();
                }            },
            新Response.Listener<串GT;(){
                @覆盖
                公共无效onResponse(字符串响应){
                    Toast.makeText(getApplicationContext(),
                            成功,Toast.LENGTH_LONG)
                            。显示();
                }            }的资源文件,sourceFile.length(),空,头,参数,可以为null);
    。VolleyController.getInstance()addToRequestQueue(multipartRequest);
}


解决方案

至于评论,我找不到你在哪里处理的头MultipartRequest类中

所以更新您的类是这样的:

 公共类MultipartRequest扩展请求<串GT; {   ...
   私人最终地图<字符串,字符串> mHeaders;
   ...    公共MultipartRequest(...,地图<字符串,字符串>头,...){
        超(...);
        ...
        this.mHeaders =头;
        ...
    }   @覆盖
   公共地图<字符串,字符串> getHeaders()抛出AuthFailureError {
       返回(mHeaders!= NULL)? mHeaders:super.getHeaders();
   }   ...
}

I have some code to send multipart request with Android Volley. But When i'm try running the code, showing error "BasicNetwork.performRequest: Unexpected response code 401".

Hope, anyone can help me. Thanks.

This My Multipartrequest.

public class MultipartRequest extends Request<String> {
  MultipartEntityBuilder entity = MultipartEntityBuilder.create();
  HttpEntity httpentity;
  private String FILE_PART_NAME = "upload";

  private final Response.Listener<String> mListener;
  private final File mFilePart;
  private final Map<String, String> mStringPart;

public MultipartRequest(String url, Response.ErrorListener errorListener,
                        Response.Listener<String> listener, File file,
                        long length, Map<String, String> mStringPart, HashMap<String, String> headers, HashMap<String, String> params, Object o) {
    super(Method.POST, url, errorListener);

    this.mListener = listener;
    this.mFilePart = file;
    this.mStringPart = mStringPart;

    entity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    try {
        entity.setCharset(CharsetUtils.get("UTF-8"));
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    buildMultipartEntity();
    httpentity = entity.build();
}

private void buildMultipartEntity() {
    entity.addPart(FILE_PART_NAME, new FileBody(mFilePart, ContentType.create("image/jpeg"), mFilePart.getName()));
    if (mStringPart != null) {
        for (Map.Entry<String, String> entry : mStringPart.entrySet()) {
            entity.addTextBody(entry.getKey(), entry.getValue());
        }
    }
}

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

@Override
public byte[] getBody() throws AuthFailureError {

    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    try
    {
        httpentity.writeTo(bos);
    }
    catch (IOException e)
    {
        VolleyLog.e("IOException writing to ByteArrayOutputStream");
    }
    return bos.toByteArray();
}

@Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {

    try {
        System.out.println("Network Response "+ new String(response.data, "UTF-8"));
        return Response.success(new String(response.data, "UTF-8"),
                getCacheEntry());
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
        return Response.success(new String(response.data), getCacheEntry());
    }
}

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

And i call multipart request like this.

 private void upload(){
    HashMap<String, String> headers = new HashMap<String, String>();
    String credentials = AppConfig.USER_API+":"+AppConfig.PASSWORD_API;
    String auth = "Basic "
            + Base64.encodeToString(credentials.getBytes(),
            Base64.NO_WRAP);
    headers.put("Authorization", auth);

    File sourceFile = new File(filePath);

    HashMap<String, String> params = new HashMap<String, String>();
    params.put("desc", "OK");

    MultipartRequest multipartRequest = new MultipartRequest(AppConfig.URL_REPORT,

            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Log.e(TAG, "Failed : " + error.getMessage());
                    Toast.makeText(getApplicationContext(),
                            error.getMessage(), Toast.LENGTH_LONG).show();
                }

            },
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    Toast.makeText(getApplicationContext(),
                            "Success", Toast.LENGTH_LONG)
                            .show();
                }

            }, sourceFile, sourceFile.length(), null, headers, params, null);
    VolleyController.getInstance().addToRequestQueue(multipartRequest);
}
解决方案

As commented, I cannot find where did you process the headers inside MultipartRequest class

So update your class like this:

public class MultipartRequest extends Request<String>{

   ...
   private final Map<String, String> mHeaders;
   ...

    public MultipartRequest(..., Map<String, String> headers, ...) {
        super(...);
        ...
        this.mHeaders = headers;
        ...
    }

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

   ...
}

这篇关于如何在Android中发送multipart请求与排球的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 13:12