欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android使用Volley实现上传文件功能

程序员文章站 2022-07-04 09:47:09
一个项目中用到的使用volley上传头像文件的例子,供大家参考,具体内容如下 /** * created by wangshihui on 2015/11/3...

一个项目中用到的使用volley上传头像文件的例子,供大家参考,具体内容如下

/**
 * created by wangshihui on 2015/11/30.
 * 上传文件
 * url:.....
  method:post
  参数:file
  接口给的参数:file 就是表单的key,传给mfilepartname;
  这是个测试类,测试上传头像没有问题,适合只上传单个文件的场景
 */
public class multipartrequest extends request<jsonobject> {
  private string mheader;
  private map<string, string> mmap;
  private string cookiefromresp = "";
  private map<string, string> headermap = new hashmap<>();
  private multipartentity entity = new multipartentity();
  private final response.listener<jsonobject> mlistener;
  private final file mfilepart;
  private string mfilepartname;

  /**
   * @param url
   * @param listener
   * @param errorlistener
   * @param file_name
   * @param file
   */
  public multipartrequest(string url, response.listener<jsonobject> listener, response.errorlistener errorlistener, string file_name,file file)
  {
    super(method.post, url, errorlistener);
    mlistener = listener;
    mfilepart = file;
    mfilepartname=file_name;
    buildmultipartentity();
  }

  /**
   * 添加文件参数
   */
  private void buildmultipartentity()
  {
    entity.addpart(mfilepartname, new filebody(mfilepart));
  }

  @override
  public string getbodycontenttype()
  {
    return entity.getcontenttype().getvalue();
  }

  @override
  public byte[] getbody() throws authfailureerror
  {
    bytearrayoutputstream bos = new bytearrayoutputstream();
    try
    {
      entity.writeto(bos);
    }
    catch (ioexception e)
    {
      volleylog.e("ioexception writing to bytearrayoutputstream");
    }
    return bos.tobytearray();
  }

  /**
   * @param response
   * @return
   */
  @override
  protected response<jsonobject> parsenetworkresponse(networkresponse response)
  {
    try {
    jsonobject jsonobject;
    system.out.println(response.headers.tostring());
    if (response.data.length != 0) {
      string jsonstring = new string(response.data, httpheaderparser.parsecharset(response.headers));
      jsonobject = new jsonobject(jsonstring);
    } else {
      jsonobject = new jsonobject();
    }
    //获取数据头
    mheader = response.headers.tostring();
    //提取cookie(jsessionid)
    pattern pattern = pattern.compile("set-cookie=.*?;");
    matcher matcher = pattern.matcher(mheader);
    if (matcher.find()) {
      cookiefromresp = matcher.group();
      cookiefromresp = cookiefromresp.substring(11, cookiefromresp.length() - 1);
      system.out.println("cookie: " + cookiefromresp);
    }
    jsonobject.put("cookie", cookiefromresp);
    return response.success(jsonobject,
        httpheaderparser.parsecacheheaders(response));
  } catch (unsupportedencodingexception e) {
    return response.error(new parseerror(e));
  } catch (jsonexception je) {
    return response.error(new parseerror(je));
  }
  }

  /**
   * @param response
   */
  @override
  protected void deliverresponse(jsonobject response)
  {
    mlistener.onresponse(response);
  }

  @override
  protected map<string, string> getparams() throws authfailureerror {
    return mmap;
  }

  /**
   * @return
   * @throws authfailureerror
   */
  @override
  public map<string, string> getheaders() throws authfailureerror {
    return headermap;
  }

  /**
   * @return
   */
  @override
  public retrypolicy getretrypolicy() {
    retrypolicy retrypolicy = new defaultretrypolicy(5000, defaultretrypolicy.default_max_retries, defaultretrypolicy.default_backoff_mult);
    return retrypolicy;
  }

  /**
   * @param cookie
   */
  //将cookie加入数据头
  public void setsendcookie(string cookie) {
    headermap.put("cookie", cookie);
  }
}

调用方法如下:

//指定url路径
string url = "http://182.92.....";
multipartrequest multipartrequest = new multipartrequest(
    url, new response.listener<jsonobject>() {
  @override
  public void onresponse(jsonobject response) {
    savesessionid(response);    
  }
}, new response.errorlistener() {
  @override
  public void onerrorresponse(volleyerror e) {
    log.e(tag, e.getmessage(), e);
    try {
      byte[] htmlbodybytes = e.networkresponse.data;
      log.e(tag, new string(htmlbodybytes), e);
    } catch (exception e1) {
      e1.printstacktrace();
    }
    toastutil.showshorttoast(usercenteractivity.this, "网络连接异常");
  }
}, "file", mselectedpicturefile);
multipartrequest.setsendcookie(loadsessionid());
multipartrequest.settag(tag);
client.addtask(multipartrequest);

private file mselectedpicturefile;
mselectedpicturefile是一个file文件,参数名是file

通信成功保存cookie

savesessionid(response);  

发送请求上传cookie

multipartrequest.setsendcookie(loadsessionid());

client是一个volley的简单封装

protected asynhttpclient client;

public class asynhttpclient {

  //volley的请求队列
  private requestqueue requestqueue;
  //保证全局变量是单一的
  private static asynhttpclient instance;

  private context mcontext;

  private asynhttpclient(context context) {
    requestqueue = volley.newrequestqueue(context);
    this.mcontext = context;
  }
  /**
   * 单列模式,让asynhttpclient在整个项目中保持只有一个
   * @param context
   * @return
   */
  public static asynhttpclient getinstance(context context) {
    if (instance==null){
      synchronized (asynhttpclient.class){
        if (instance==null){
          instance=new asynhttpclient(context);
        }
      }
    }
    return instance;
  }

  /**
   * 添加任务到volley的请求队列中去,并不会立即执行
   * @param task
   */
  public void addtask(request task){
    requestqueue.add(task);
  }

  public requestqueue getrequestqueue() {
    return requestqueue;
  }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。