Java 如何在Android中通过截击发送多部分请求

Java 如何在Android中通过截击发送多部分请求,java,android,android-volley,Java,Android,Android Volley,我有一些代码可以用Android Volley发送多部分请求。但当我尝试运行代码时,显示错误“BasicNetwork.performRequest:意外响应代码401” 希望,任何人都能帮助我。谢谢 这是我的多方请求 public class MultipartRequest extends Request<String> { MultipartEntityBuilder entity = MultipartEntityBuilder.create(); HttpEntit

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

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

这是我的多方请求

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);
}
}
public类MultipartRequest扩展请求{
MultipartEntityBuilder实体=MultipartEntityBuilder.create();
HttpEntity HttpEntity;
私有字符串文件\u PART\u NAME=“上传”;
私人最终回应。监听器;
私有最终文件mFilePart;
私人最终地图mStringPart;
公共多部分请求(字符串url,Response.ErrorListener ErrorListener,
Response.Listener侦听器,文件,
长长度、映射mStringPart、HashMap头、HashMap参数、对象o){
super(Method.POST、url、errorListener);
this.mListener=侦听器;
this.mFilePart=文件;
this.mStringPart=mStringPart;
entity.setMode(HttpMultipartMode.BROWSER_兼容);
试一试{
entity.setCharset(CharsetUtils.get(“UTF-8”);
}捕获(不支持的编码异常e){
e、 printStackTrace();
}
buildMultipartEntity();
httpentity=entity.build();
}
私有void buildMultipartEntity(){
entity.addPart(文件名、新文件体(mFilePart、ContentType.create(“image/jpeg”)、mFilePart.getName());
if(mStringPart!=null){
对于(Map.Entry:mStringPart.entrySet()){
entity.addTextBody(entry.getKey(),entry.getValue());
}
}
}
@凌驾
公共字符串getBodyContentType(){
返回httpentity.getContentType().getValue();
}
@凌驾
公共字节[]getBody()抛出AuthFailureError{
ByteArrayOutputStream bos=新建ByteArrayOutputStream();
尝试
{
httpentity.writeTo(bos);
}
捕获(IOE异常)
{
e(“向ByteArrayOutputStream写入IOException”);
}
返回bos.toByteArray();
}
@凌驾
受保护的响应parseNetworkResponse(NetworkResponse响应){
试一试{
System.out.println(“网络响应”+新字符串(Response.data,“UTF-8”);
返回Response.success(新字符串(Response.data,“UTF-8”),
getCacheEntry());
}捕获(不支持的编码异常e){
e、 printStackTrace();
返回Response.success(新字符串(Response.data),getCacheEntry());
}
}
@凌驾
受保护的void deliverResponse(字符串响应){
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);
}
private void upload(){
HashMap headers=新的HashMap();
字符串凭据=AppConfig.USER_API+:“+AppConfig.PASSWORD_API;
字符串auth=“基本”
+Base64.encodeToString(credentials.getBytes(),
Base64.无包装);
headers.put(“授权”,auth);
文件源文件=新文件(文件路径);
HashMap params=新的HashMap();
参数put(“描述”、“确定”);
MultipartRequest MultipartRequest=新的MultipartRequest(AppConfig.URL\u报告,
新的Response.ErrorListener(){
@凌驾
公共无效onErrorResponse(截击错误){
Log.e(标记“Failed:+error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(),Toast.LENGTH_LONG).show();
}
},
新的Response.Listener(){
@凌驾
公共void onResponse(字符串响应){
Toast.makeText(getApplicationContext(),
“成功”,祝酒词。长度(长)
.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();
   }

   ...
}
public类MultipartRequest扩展请求{
...
私人最终地图管理员;
...
公共多部分请求(…,映射头…){
超级(…);
...
this.mHeaders=标题;
...
}
@凌驾
公共映射getHeaders()引发AuthFailureError{
返回(mHeaders!=null)?mHeaders:super.getHeaders();
}
...
}

我找不到您在MultipartRequest类中处理标题的位置。很高兴这能有所帮助:-)为什么我提交到显示错误500的上传数据?500内部服务器错误可能是由于许多原因,您能检查/调试服务器端应用程序吗?那么在9月12日,你说这对你有用呢?