自定义 request
public class MultiPartRequest extends JsonRequest<JSONObject> {
/* To hold the parameter name and the File to upload */
private Map<String,File> fileUploads = new HashMap<String,File>();
/* To hold the parameter name and the string content to upload */
private Map<String,String> stringUploads = new HashMap<String,String>();
private Map<String, String> headers = new HashMap<String, String>();
public MultiPartRequest(int method, String url, JSONObject jsonRequest,
Listener<JSONObject> listener, ErrorListener errorListener) {
super(method, url, (jsonRequest == null) ? null : jsonRequest.toString(), listener,
errorListener);
}
public MultiPartRequest(String url, JSONObject jsonRequest, Listener<JSONObject> listener,
ErrorListener errorListener) {
this(jsonRequest == null ? Method.GET : Method.POST, url, jsonRequest,
listener, errorListener);
}
public void addFileUpload(String param,File file) {
fileUploads.put(param,file);
}
public void addStringUpload(String param,String content) {
stringUploads.put(param,content);
}
public Map<String,File> getFileUploads() {
return fileUploads;
}
public Map<String,String> getStringUploads() {
return stringUploads;
}
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
return headers;
}
public void setHeader(String title, String content) {
headers.put(title, content);
}
@Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
try {
String jsonString =
new String(response.data, HttpHeaderParser.parseCharset(response.headers));
return Response.success(new JSONObject(jsonString),
HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JSONException je) {
return Response.error(new ParseError(je));
}
}
}
还需要 自定义HttpStack
<pre name="code" class="java">public class SslHttpStack implements HttpStack {
private boolean mIsConnectingToYourServer = false;
private final static String HEADER_CONTENT_TYPE = "Content-Type";
private Context mContext;
public SslHttpStack(boolean isYourServer,Context context) {
mIsConnectingToYourServer = isYourServer;
mContext=context;
}
private static void addHeaders(HttpUriRequest httpRequest, Map<String, String> headers) {
for (String key : headers.keySet()) {
httpRequest.setHeader(key, headers.get(key));
}
}
@SuppressWarnings("unused")
private static List<NameValuePair> getPostParameterPairs(Map<String, String> postParams) {
List<NameValuePair> result = new ArrayList<NameValuePair>(postParams.size());
for (String key : postParams.keySet()) {
result.add(new BasicNameValuePair(key, postParams.get(key)));
}
return result;
}
@Override
public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders)
throws IOException, AuthFailureError {
Log.e("performRequest", "");
HttpUriRequest post = createHttpRequest(request, additionalHeaders);
addHeaders(post, additionalHeaders);
addHeaders(post, request.getHeaders());
onPrepareRequest(post);
HttpParams params = post.getParams();
int timeoutMs = request.getTimeoutMs();
HttpConnectionParams.setConnectionTimeout(params, 5000);
HttpConnectionParams.setSoTimeout(params, timeoutMs);
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("http", new PlainSocketFactory(), 80));
registry.register(new Scheme("https", new EasySSLSocketFactory(mIsConnectingToYourServer,mContext), 443));
ThreadSafeClientConnManager manager = new ThreadSafeClientConnManager(params, registry);
HttpClient httpClient = new DefaultHttpClient(manager, params);
return httpClient.execute(post);
}
/**
* Creates the appropriate subclass of HttpUriRequest for passed in request.
*/
@SuppressWarnings("deprecation")
/* protected */ static HttpUriRequest createHttpRequest(Request<?> request,
Map<String, String> additionalHeaders) throws AuthFailureError {
switch (request.getMethod()) {
case Method.DEPRECATED_GET_OR_POST: {
// This is the deprecated way that needs to be handled for backwards compatibility.
// If the request's post body is null, then the assumption is that the request is
// GET. Otherwise, it is assumed that the request is a POST.
byte[] postBody = request.getPostBody();
if (postBody != null) {
HttpPost postRequest = new HttpPost(request.getUrl());
postRequest.addHeader(HEADER_CONTENT_TYPE, request.getPostBodyContentType());
HttpEntity entity;
entity = new ByteArrayEntity(postBody);
postRequest.setEntity(entity);
return postRequest;
} else {
return new HttpGet(request.getUrl());
}
}
case Method.GET:
return new HttpGet(request.getUrl());
case Method.DELETE:
return new HttpDelete(request.getUrl());
case Method.POST: {
HttpPost post= new HttpPost(((MultiPartRequest)request).getUrl());
// post.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType()); 上传无效
setMultiPartBody(post,request);
setEntityIfNonEmptyBody(post, request);
Log.e("post", "request"+"");
return post;
}
case Method.PUT: {
HttpPut putRequest = new HttpPut(request.getUrl());
putRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
setMultiPartBody(putRequest,request);
setEntityIfNonEmptyBody(putRequest, request);
return putRequest;
}
// Added in source code of Volley libray.
// case Method.PATCH: {
// HttpPatch patchRequest = new HttpPatch(request.getUrl());
// patchRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
// setEntityIfNonEmptyBody(patchRequest, request);
// return patchRequest;
// }
default:
throw new IllegalStateException("Unknown request method.");
}
}
private static void setEntityIfNonEmptyBody(HttpEntityEnclosingRequestBase httpRequest,
Request<?> request) throws AuthFailureError {
byte[] body = request.getBody();
if (body != null) {
HttpEntity entity = new ByteArrayEntity(body);
httpRequest.setEntity(entity);
}
}
private static void setMultiPartBody(HttpEntityEnclosingRequestBase httpRequest,
Request<?> request) throws AuthFailureError {
// Return if Request is not MultiPartRequest
if(request instanceof MultiPartRequest == false) {
return;
}
MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
Map<String,File> fileUpload = ((MultiPartRequest)request).getFileUploads();
for (Map.Entry<String, File> entry : fileUpload.entrySet()) {
System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
multipartEntity.addPart(new FormBodyPart(((String)entry.getKey()), new FileBody((File)entry.getValue())));
// multipartEntity.addPart(((String)entry.getKey()), new FileBody((File)entry.getValue(),"text/plain"));
}
Map<String,String> stringUpload = ((MultiPartRequest)request).getStringUploads();
for (Map.Entry<String, String> entry : stringUpload.entrySet()) {
System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
try {
multipartEntity.addPart(((String)entry.getKey()), new StringBody((String)entry.getValue(),Charset.forName("UTF-8")));
} catch (Exception e) {
e.printStackTrace();
}
}
httpRequest.setEntity(multipartEntity);
}
/**
* Called before the request is executed using the underlying HttpClient.
*
* <p>Overwrite in subclasses to augment the request.</p>
*/
protected void onPrepareRequest(HttpUriRequest request) throws IOException {
// Nothing.
}
}
public static void VolleyUpload(Context c) {
try {
final RequestQueue requestQueue = Volley.newRequestQueue(c,
new SslHttpStack(false, c));
MultiPartRequest multi = new MultiPartRequest(Request.Method.POST,
"http://localhost:8080/myweb/der", null,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject arg0) {
Log.e("success", "上传成功");
// requestQueue.cancelAll("uploads");
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError arg0) {
Log.e("arg0", arg0.getMessage().toString());
}
});
// 测试文件
File file = new File(c.getCacheDir(), "juntao.txt");
if (!file.exists()) {
file.createNewFile();
}
FileWriter w = new FileWriter(file);
w.write("馒头");
w.flush();
multi.addFileUpload("file", file);
multi.addStringUpload("title", "黑麦面包");
requestQueue.add(multi);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}