Android uses Volley to upload files

  • 2021-10-27 09:16:05
  • OfStack

1 project used in the use of Volley upload avatar file example, for your reference, the specific content is as follows


/**
 * Created by wangshihui on 2015/11/30.
 *  Upload a file 
 * url : .....
  method : post
   Parameters: file
   Parameters given by the interface: file  Is the form's key , pass to mFilePartName;
   This is a test class. There is no problem in uploading avatars. It is suitable for uploading only a single file 
 */
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();
  }

  /**
   *  Add file parameters 
   */
  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();
    }
    // Get data header 
    mHeader = response.headers.toString();
    // Extraction 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
   */
  // Will Cookie Add a data header 
  public void setSendCookie(String cookie) {
    headerMap.put("Cookie", cookie);
  }
}

The call method is as follows:


// Specify url Path 
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, " Network connection exception ");
  }
}, "file", mSelectedPictureFile);
multipartRequest.setSendCookie(loadSessionID());
multipartRequest.setTag(TAG);
client.addTask(multipartRequest);

private File mSelectedPictureFile;
mSelectedPictureFile is an File file with the parameter name file

Communication successfully saved Cookie

saveSessionID(response);

Send Request Upload cookie

multipartRequest.setSendCookie(loadSessionID());

client is a simple package of an Volley

protected AsynHttpClient client;


public class AsynHttpClient {

  //volley Request queue of 
  private RequestQueue requestQueue;
  // Ensure that global variables are single 1 Adj. 
  private static AsynHttpClient instance;

  private Context mContext;

  private AsynHttpClient(Context context) {
    requestQueue = Volley.newRequestQueue(context);
    this.mContext = context;
  }
  /**
   *  Single-column mode, let AsynHttpClient Maintain only 1 A 
   * @param context
   * @return
   */
  public static AsynHttpClient getInstance(Context context) {
    if (instance==null){
      synchronized (AsynHttpClient.class){
        if (instance==null){
          instance=new AsynHttpClient(context);
        }
      }
    }
    return instance;
  }

  /**
   *  Add a task to the volley Request queue, and will not be executed immediately 
   * @param task
   */
  public void addTask(Request task){
    requestQueue.add(task);
  }

  public RequestQueue getRequestQueue() {
    return requestQueue;
  }
}


Related articles: