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

发布时间:2020-09-30 16:02:00 作者:王世晖
来源:脚本之家 阅读:130

一个项目中用到的使用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;
  }
}

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

推荐阅读:
  1. Volley框架的使用
  2. android Volley 使用

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

android volley 上传文件

上一篇:php如何实现二级联动菜单

下一篇:django商品分类及商品数据建模实例详解

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》