Skip to content

Instantly share code, notes, and snippets.

@alphamu
Last active October 26, 2017 06:06
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save alphamu/684d8ae311d95831ce1c to your computer and use it in GitHub Desktop.
Save alphamu/684d8ae311d95831ce1c to your computer and use it in GitHub Desktop.
An implementation of Request<String> for Google Volley which posts data using `multipart/form-data`. Volley by default uses `application/x-www-form-urlencoded` which may not be supported by all services.
import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.HttpHeaderParser;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Map;
import ch.boye.httpclientandroidlib.HttpEntity;
import ch.boye.httpclientandroidlib.entity.mime.MultipartEntityBuilder;
public class MultipartRequest extends Request<String> {
private HttpEntity mHttpEntity;
private MultipartEntityBuilder builder = MultipartEntityBuilder.create();
private final Response.Listener<String> mListener;
private final Map<String, String> mKeyValue;
public MultipartRequest(String url, Map<String, String> params, Response.Listener<String> listener, Response.ErrorListener errorListener) {
super(Method.POST, url, errorListener);
mListener = listener;
mKeyValue = params;
buildMultipartEntity();
}
private void buildMultipartEntity() {
for (Map.Entry<String, String> entry : mKeyValue.entrySet()) {
builder.addTextBody(entry.getKey(), entry.getValue());
}
mHttpEntity = builder.build();
}
@Override
public String getBodyContentType() {
return mHttpEntity.getContentType().getValue();
}
@Override
public byte[] getBody() throws AuthFailureError {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
mHttpEntity.writeTo(bos);
} catch (IOException e) {
VolleyLog.e("IOException writing to ByteArrayOutputStream");
}
return bos.toByteArray();
}
@Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
String jsonString = "";
try {
jsonString = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return Response.success(jsonString, getCacheEntry());
}
@Override
protected void deliverResponse(String response) {
mListener.onResponse(response);
}
}
RequestQueue requestQueue = VolleySingleton.getInstance().getRequestQueue();
HashMap<String, String> params = new HashMap<String, String>();
MultipartRequest multipartRequest =
new MultipartRequest(mServerUrl, params, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
//Do Something
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// Handle your error types accordingly.For Timeout & No connection error, you can show 'retry' button.
// For AuthFailure, you can re login with user credentials.
// For ClientError, 400 & 401, Errors happening on client side when sending api request.
// In this case you can check how client is forming the api and debug accordingly.
// For ServerError 5xx, you can do retry or handle accordingly.
if (error instanceof NetworkError) {
} else if (error instanceof ServerError) {
} else if (error instanceof AuthFailureError) {
} else if (error instanceof ParseError) {
} else if (error instanceof NoConnectionError) {
} else if (error instanceof TimeoutError) {
}
}
});
requestQueue.add(multipartRequest);
@00imvj00
Copy link

00imvj00 commented Oct 7, 2015

i am having http entity error

@fardin95
Copy link

fardin95 commented Jan 7, 2016

Where MultipartEntityBuilder entity...

@hackaprende
Copy link

How would you set a parameter if you want to pass a JSONArray of objects?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment