因爲volley默認使用的HttpStack是HttpUrlConnection, 因此咱們須要手動指定用HttpClient
java
mRequestQueue = Volley.newRequestQueue(mCtx.getApplicationContext(), new HttpClientStack(new DefaultHttpClient()));ide
使用HttpUrlConnection的方式上傳文件對body的格式要求較嚴格, 構造起來較麻煩, 若是實在要用HttpUrlConnection, 能夠參考http://www.codejava.net/java-se/networking/upload-files-by-sending-multipart-request-programmatically. 如下是我寫的MultipartRequest:ui
public class MultipartRequest extends Request { private Response.Listener mListener; private HttpEntity mEntity; public MultipartRequest(Map<String, String> textBodyParamMap, Map<String, File> fileBodyParamMap, Response.Listener listener, Response.ErrorListener errorListener) { super(Method.POST, YOUR_URL, errorListener); mListener = listener; Charset charset = Charset.forName("UTF-8"); ContentType contentType = ContentType.create("text/plain", charset); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE).setCharset(charset); for (Map.Entry<String, String> entry : textBodyParamMap.entrySet()) { builder.addTextBody(entry.getKey(), entry.getValue(), contentType); } for (Map.Entry<String, File> entry : fileBodyParamMap.entrySet()) { builder.addBinaryBody(entry.getKey(), entry.getValue()); } mEntity = builder.build(); } @Override public Map<String, String> getHeaders() throws AuthFailureError { Map<String, String> headers = new HashMap<String, String>(); headers.put(HTTP.CHARSET_PARAM, HTTP.UTF_8); return headers; } @Override public String getBodyContentType() { return mEntity.getContentType().getValue(); } @Override public byte[] getBody() { ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { mEntity.writeTo(baos); } catch (IOException e) { e.printStackTrace(); } return baos.toByteArray(); } @Override protected Response parseNetworkResponse(NetworkResponse response) { JSONObject jo = null; try { jo = new JSONObject(new String(response.data, HttpHeaderParser.parseCharset(response.headers))); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } return Response.success(jo, HttpHeaderParser.parseCacheHeaders(response)); } @Override protected void deliverResponse(Object response) { mListener.onResponse(response); } }