All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.loopj.android.http.RequestParams Maven / Gradle / Ivy

There is a newer version: 1.4.11
Show newest version
/*
    Android Asynchronous Http Client
    Copyright (c) 2011 James Smith 
    http://loopj.com

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

        http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
*/

package com.loopj.android.http;

import android.util.Log;

import org.apache.http.HttpEntity;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * A collection of string request parameters or files to send along with requests made from an
 * {@link AsyncHttpClient} instance. 

 

For example:

 

*
 * RequestParams params = new RequestParams();
 * params.put("username", "james");
 * params.put("password", "123456");
 * params.put("email", "my@email.com");
 * params.put("profile_picture", new File("pic.jpg")); // Upload a File
 * params.put("profile_picture2", someInputStream); // Upload an InputStream
 * params.put("profile_picture3", new ByteArrayInputStream(someBytes)); // Upload some bytes
 *
 * Map<String, String> map = new HashMap<String, String>();
 * map.put("first_name", "James");
 * map.put("last_name", "Smith");
 * params.put("user", map); // url params: "user[first_name]=James&user[last_name]=Smith"
 *
 * Set<String> set = new HashSet<String>(); // unordered collection
 * set.add("music");
 * set.add("art");
 * params.put("like", set); // url params: "like=music&like=art"
 *
 * List<String> list = new ArrayList<String>(); // Ordered collection
 * list.add("Java");
 * list.add("C");
 * params.put("languages", list); // url params: "languages[]=Java&languages[]=C"
 *
 * String[] colors = { "blue", "yellow" }; // Ordered collection
 * params.put("colors", colors); // url params: "colors[]=blue&colors[]=yellow"
 *
 * List<Map<String, String>> listOfMaps = new ArrayList<Map<String,
 * String>>();
 * Map<String, String> user1 = new HashMap<String, String>();
 * user1.put("age", "30");
 * user1.put("gender", "male");
 * Map<String, String> user2 = new HashMap<String, String>();
 * user2.put("age", "25");
 * user2.put("gender", "female");
 * listOfMaps.add(user1);
 * listOfMaps.add(user2);
 * params.put("users", listOfMaps); // url params: "users[][age]=30&users[][gender]=male&users[][age]=25&users[][gender]=female"
 *
 * AsyncHttpClient client = new AsyncHttpClient();
 * client.post("http://myendpoint.com", params, responseHandler);
 * 
*/ public class RequestParams { public final static String APPLICATION_OCTET_STREAM = "application/octet-stream"; public final static String APPLICATION_JSON = "application/json"; protected final static String LOG_TAG = "RequestParams"; protected boolean isRepeatable; protected boolean useJsonStreamer; protected boolean autoCloseInputStreams; protected final ConcurrentHashMap urlParams = new ConcurrentHashMap(); protected final ConcurrentHashMap streamParams = new ConcurrentHashMap(); protected final ConcurrentHashMap fileParams = new ConcurrentHashMap(); protected final ConcurrentHashMap urlParamsWithObjects = new ConcurrentHashMap(); protected String contentEncoding = HTTP.UTF_8; /** * Sets content encoding for return value of {@link #getParamString()} and {@link * #createFormEntity()}

 

Default encoding is "UTF-8" * * @param encoding String constant from {@link org.apache.http.protocol.HTTP} */ public void setContentEncoding(final String encoding) { if (encoding != null) this.contentEncoding = encoding; else Log.d(LOG_TAG, "setContentEncoding called with null attribute"); } /** * Constructs a new empty {@code RequestParams} instance. */ public RequestParams() { this((Map) null); } /** * Constructs a new RequestParams instance containing the key/value string params from the * specified map. * * @param source the source key/value string map to add. */ public RequestParams(Map source) { if (source != null) { for (Map.Entry entry : source.entrySet()) { put(entry.getKey(), entry.getValue()); } } } /** * Constructs a new RequestParams instance and populate it with a single initial key/value * string param. * * @param key the key name for the intial param. * @param value the value string for the initial param. */ public RequestParams(final String key, final String value) { this(new HashMap() {{ put(key, value); }}); } /** * Constructs a new RequestParams instance and populate it with multiple initial key/value * string param. * * @param keysAndValues a sequence of keys and values. Objects are automatically converted to * Strings (including the value {@code null}). * @throws IllegalArgumentException if the number of arguments isn't even. */ public RequestParams(Object... keysAndValues) { int len = keysAndValues.length; if (len % 2 != 0) throw new IllegalArgumentException("Supplied arguments must be even"); for (int i = 0; i < len; i += 2) { String key = String.valueOf(keysAndValues[i]); String val = String.valueOf(keysAndValues[i + 1]); put(key, val); } } /** * Adds a key/value string pair to the request. * * @param key the key name for the new param. * @param value the value string for the new param. */ public void put(String key, String value) { if (key != null && value != null) { urlParams.put(key, value); } } /** * Adds a file to the request. * * @param key the key name for the new param. * @param file the file to add. * @throws java.io.FileNotFoundException throws if wrong File argument was passed */ public void put(String key, File file) throws FileNotFoundException { put(key, file, null); } /** * Adds a file to the request. * * @param key the key name for the new param. * @param file the file to add. * @param contentType the content type of the file, eg. application/json * @throws java.io.FileNotFoundException throws if wrong File argument was passed */ public void put(String key, File file, String contentType) throws FileNotFoundException { if (file == null || !file.exists()) { throw new FileNotFoundException(); } if (key != null) { fileParams.put(key, new FileWrapper(file, contentType)); } } /** * Adds an input stream to the request. * * @param key the key name for the new param. * @param stream the input stream to add. */ public void put(String key, InputStream stream) { put(key, stream, null); } /** * Adds an input stream to the request. * * @param key the key name for the new param. * @param stream the input stream to add. * @param name the name of the stream. */ public void put(String key, InputStream stream, String name) { put(key, stream, name, null); } /** * Adds an input stream to the request. * * @param key the key name for the new param. * @param stream the input stream to add. * @param name the name of the stream. * @param contentType the content type of the file, eg. application/json */ public void put(String key, InputStream stream, String name, String contentType) { put(key, stream, name, contentType, autoCloseInputStreams); } /** * Adds an input stream to the request. * * @param key the key name for the new param. * @param stream the input stream to add. * @param name the name of the stream. * @param contentType the content type of the file, eg. application/json * @param autoClose close input stream automatically on successful upload */ public void put(String key, InputStream stream, String name, String contentType, boolean autoClose) { if (key != null && stream != null) { streamParams.put(key, StreamWrapper.newInstance(stream, name, contentType, autoClose)); } } /** * Adds param with non-string value (e.g. Map, List, Set). * * @param key the key name for the new param. * @param value the non-string value object for the new param. */ public void put(String key, Object value) { if (key != null && value != null) { urlParamsWithObjects.put(key, value); } } /** * Adds a int value to the request. * * @param key the key name for the new param. * @param value the value int for the new param. */ public void put(String key, int value) { if (key != null) { urlParams.put(key, String.valueOf(value)); } } /** * Adds a long value to the request. * * @param key the key name for the new param. * @param value the value long for the new param. */ public void put(String key, long value) { if (key != null) { urlParams.put(key, String.valueOf(value)); } } /** * Adds string value to param which can have more than one value. * * @param key the key name for the param, either existing or new. * @param value the value string for the new param. */ public void add(String key, String value) { if (key != null && value != null) { Object params = urlParamsWithObjects.get(key); if (params == null) { // Backward compatible, which will result in "k=v1&k=v2&k=v3" params = new HashSet(); this.put(key, params); } if (params instanceof List) { ((List) params).add(value); } else if (params instanceof Set) { ((Set) params).add(value); } } } /** * Removes a parameter from the request. * * @param key the key name for the parameter to remove. */ public void remove(String key) { urlParams.remove(key); streamParams.remove(key); fileParams.remove(key); urlParamsWithObjects.remove(key); } /** * Check if a parameter is defined. * * @param key the key name for the parameter to check existence. * @return Boolean */ public boolean has(String key) { return urlParams.get(key) != null || streamParams.get(key) != null || fileParams.get(key) != null || urlParamsWithObjects.get(key) != null; } @Override public String toString() { StringBuilder result = new StringBuilder(); for (ConcurrentHashMap.Entry entry : urlParams.entrySet()) { if (result.length() > 0) result.append("&"); result.append(entry.getKey()); result.append("="); result.append(entry.getValue()); } for (ConcurrentHashMap.Entry entry : streamParams.entrySet()) { if (result.length() > 0) result.append("&"); result.append(entry.getKey()); result.append("="); result.append("STREAM"); } for (ConcurrentHashMap.Entry entry : fileParams.entrySet()) { if (result.length() > 0) result.append("&"); result.append(entry.getKey()); result.append("="); result.append("FILE"); } List params = getParamsList(null, urlParamsWithObjects); for (BasicNameValuePair kv : params) { if (result.length() > 0) result.append("&"); result.append(kv.getName()); result.append("="); result.append(kv.getValue()); } return result.toString(); } public void setHttpEntityIsRepeatable(boolean isRepeatable) { this.isRepeatable = isRepeatable; } public void setUseJsonStreamer(boolean useJsonStreamer) { this.useJsonStreamer = useJsonStreamer; } /** * Set global flag which determines whether to automatically close input streams on successful * upload. * * @param flag boolean whether to automatically close input streams */ public void setAutoCloseInputStreams(boolean flag) { autoCloseInputStreams = flag; } /** * Returns an HttpEntity containing all request parameters. * * @param progressHandler HttpResponseHandler for reporting progress on entity submit * @return HttpEntity resulting HttpEntity to be included along with {@link * org.apache.http.client.methods.HttpEntityEnclosingRequestBase} * @throws IOException if one of the streams cannot be read */ public HttpEntity getEntity(ResponseHandlerInterface progressHandler) throws IOException { if (useJsonStreamer) { return createJsonStreamerEntity(progressHandler); } else if (streamParams.isEmpty() && fileParams.isEmpty()) { return createFormEntity(); } else { return createMultipartEntity(progressHandler); } } private HttpEntity createJsonStreamerEntity(ResponseHandlerInterface progressHandler) throws IOException { JsonStreamerEntity entity = new JsonStreamerEntity(progressHandler, !fileParams.isEmpty() || !streamParams.isEmpty()); // Add string params for (ConcurrentHashMap.Entry entry : urlParams.entrySet()) { entity.addPart(entry.getKey(), entry.getValue()); } // Add non-string params for (ConcurrentHashMap.Entry entry : urlParamsWithObjects.entrySet()) { entity.addPart(entry.getKey(), entry.getValue()); } // Add file params for (ConcurrentHashMap.Entry entry : fileParams.entrySet()) { entity.addPart(entry.getKey(), entry.getValue()); } // Add stream params for (ConcurrentHashMap.Entry entry : streamParams.entrySet()) { StreamWrapper stream = entry.getValue(); if (stream.inputStream != null) { entity.addPart(entry.getKey(), StreamWrapper.newInstance( stream.inputStream, stream.name, stream.contentType, stream.autoClose) ); } } return entity; } private HttpEntity createFormEntity() { try { return new UrlEncodedFormEntity(getParamsList(), contentEncoding); } catch (UnsupportedEncodingException e) { Log.e(LOG_TAG, "createFormEntity failed", e); return null; // Can happen, if the 'contentEncoding' won't be HTTP.UTF_8 } } private HttpEntity createMultipartEntity(ResponseHandlerInterface progressHandler) throws IOException { SimpleMultipartEntity entity = new SimpleMultipartEntity(progressHandler); entity.setIsRepeatable(isRepeatable); // Add string params for (ConcurrentHashMap.Entry entry : urlParams.entrySet()) { entity.addPartWithCharset(entry.getKey(), entry.getValue(), contentEncoding); } // Add non-string params List params = getParamsList(null, urlParamsWithObjects); for (BasicNameValuePair kv : params) { entity.addPartWithCharset(kv.getName(), kv.getValue(), contentEncoding); } // Add stream params for (ConcurrentHashMap.Entry entry : streamParams.entrySet()) { StreamWrapper stream = entry.getValue(); if (stream.inputStream != null) { entity.addPart(entry.getKey(), stream.name, stream.inputStream, stream.contentType); } } // Add file params for (ConcurrentHashMap.Entry entry : fileParams.entrySet()) { FileWrapper fileWrapper = entry.getValue(); entity.addPart(entry.getKey(), fileWrapper.file, fileWrapper.contentType); } return entity; } protected List getParamsList() { List lparams = new LinkedList(); for (ConcurrentHashMap.Entry entry : urlParams.entrySet()) { lparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); } lparams.addAll(getParamsList(null, urlParamsWithObjects)); return lparams; } private List getParamsList(String key, Object value) { List params = new LinkedList(); if (value instanceof Map) { Map map = (Map) value; List list = new ArrayList(map.keySet()); // Ensure consistent ordering in query string if (list.size() > 0 && list.get(0) instanceof Comparable) { Collections.sort(list); } for (Object nestedKey : list) { if (nestedKey instanceof String) { Object nestedValue = map.get(nestedKey); if (nestedValue != null) { params.addAll(getParamsList(key == null ? (String) nestedKey : String.format("%s[%s]", key, nestedKey), nestedValue)); } } } } else if (value instanceof List) { List list = (List) value; int listSize = list.size(); for (int nestedValueIndex = 0; nestedValueIndex < listSize; nestedValueIndex++) { params.addAll(getParamsList(String.format("%s[%d]", key, nestedValueIndex), list.get(nestedValueIndex))); } } else if (value instanceof Object[]) { Object[] array = (Object[]) value; int arrayLength = array.length; for (int nestedValueIndex = 0; nestedValueIndex < arrayLength; nestedValueIndex++) { params.addAll(getParamsList(String.format("%s[%d]", key, nestedValueIndex), array[nestedValueIndex])); } } else if (value instanceof Set) { Set set = (Set) value; for (Object nestedValue : set) { params.addAll(getParamsList(key, nestedValue)); } } else { params.add(new BasicNameValuePair(key, value.toString())); } return params; } protected String getParamString() { return URLEncodedUtils.format(getParamsList(), contentEncoding); } public static class FileWrapper { public final File file; public final String contentType; public FileWrapper(File file, String contentType) { this.file = file; this.contentType = contentType; } } public static class StreamWrapper { public final InputStream inputStream; public final String name; public final String contentType; public final boolean autoClose; public StreamWrapper(InputStream inputStream, String name, String contentType, boolean autoClose) { this.inputStream = inputStream; this.name = name; this.contentType = contentType; this.autoClose = autoClose; } static StreamWrapper newInstance(InputStream inputStream, String name, String contentType, boolean autoClose) { return new StreamWrapper( inputStream, name, contentType == null ? APPLICATION_OCTET_STREAM : contentType, autoClose); } } }