我有一些代码可以通过Android Volley发送多部分请求。但是,当我尝试运行代码时,显示错误“ BasicNetwork.performRequest:意外的响应代码401”。

希望任何人都能帮助我。谢谢。

这是我的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);
}
}


我这样叫多部分请求。

 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);
}

最佳答案

如前所述,我找不到您在哪里处理了MultipartRequest类中的标头

因此,像这样更新您的课程:

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();
   }

   ...
}

10-08 19:10