您好,登錄后才能下訂單哦!
一個項目中用到的使用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; } }
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持億速云。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。