Category Archives: android-volley

Send bitmaps to backend (Android)

Here is an old code to stream bytes. We want to incorporate android's volley to send images back to the server. I am wondering if someone on stackoverflow can tell me new libraries to update this old code.

One we are currently thinking about is Square's Retro.

The code is from org.apache.

 public class MultipartRequest extends Request<String>{
        private MultipartEntityBuilder mEntity = MultipartEntityBuilder.create();
        private HttpEntity mHttpEntity;
        private final Response.Listener<String> mListener;
        private final File mFilePart;
        private static final String TAG = "MultipartRequest";
        private static final boolean DEBUG = true;

        public MultipartRequest(String url, Response.ErrorListener errorListener, Response.Listener<String> listener, File file){
            super(Method.POST, url, errorListener);
            mListener = listener;
            mFilePart = file;
            mHttpEntity =;

        public void buildMultipartEntity(){
            mEntity.addBinaryBody("avatar", mFilePart);

        public String getBodyContentType(){
            return mHttpEntity.getContentType().getValue();

        public byte[] getBody() throws AuthFailureError{
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            catch (IOException e){
                if (DEBUG) Log.d(TAG, "IOException writing to ByteArrayOutputStream");
            return bos.toByteArray();

        protected Response<String> parseNetworkResponse(NetworkResponse response){
            return Response.success("Uploaded", getCacheEntry());

        protected void deliverResponse(String response){


Set charset dynamically on every request httpd/AWS

I have an Android app using volley to request the server and I set the header like this:

headers.put("Content-Type", "application/json");

The server is a Django (1.8) project running on AWS-EB. When I run it as

$ python runserver

It works perfectly.

But when I deploy the server and it's running over httpd, the only way to make it works is setting the requests header as:

headers.put("Content-Type", "application/json; charset=UTF-8");

This is a good solution for future releases but I need backward compatibility with older android versions.

Do you have any idea how to fix this on server side?

I have already tried with AddDefaultCharset utf-8 but it didn't work.

Getting Android Volley null error after calling specific php functions, other functions work fine

I've got an android application which communicates with a webserver using PHP and Volley. My app sends a Post request to a Listener.php file on my webserver and chooses different functions in a Functions.php. The problem is: some functions lead to a volley null error although the code is executed. Theres no error in apache erroglog and I can see the data change in my database. But I want to process a response in my app which is not possible when I get this error. The webserver is running on my raspberry pi now and I get this error all the time when calling specific functions, other functions are working as expected. When I test the same code on Windows its working fine (although these null errors are happening too from time to time at the same functions). I really hope theres someone to put me in the right direction, I have no idea how to proceed with that kind of problem..

Java/Volley Post

  public static void importNewMedia(final Context context) {

    final String TAG = "importMedia";
    String tag_string_req = "admin_control";
    StringRequest strReq = new StringRequest(,
            AppConfig.URL_SERVER, new Response.Listener<String>() {

        public void onResponse(String response) {
            Log.d(TAG, response.toString());
            try {
                JSONObject jObj = new JSONObject(response);
                boolean error = jObj.getBoolean("error");
                if (!error) {

                    Toast.makeText(context, "Database has been updated!", Toast.LENGTH_SHORT).show();

                } else {

                            "Database has not been updated!", Toast.LENGTH_SHORT).show();

            } catch (JSONException e) {

                Toast.makeText(context, "0"+
                        " Database has not been updated!", Toast.LENGTH_SHORT).show();

    }, new Response.ErrorListener() {
        public void onErrorResponse(VolleyError error) {
            Log.e(TAG, "Connection Error: " + error.getMessage());

    }) {
        protected Map<String, String> getParams() {
            HashMap<String ,String> params=new HashMap<String, String>();
            params.put("tag", "getNewMedia");
            return params;
    // Adding request to request queue
    AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
    System.out.println(strReq + tag_string_req);



else if ($tag == 'getNewMedia') {    


     if ($test ) {

        $response["error"] = FALSE;
        echo json_encode($response);

    } else {

        $response["error"] = TRUE;
        $response["error_msg"] = "Server Error";
        echo json_encode(array_values($response));

One of the Functions that causes null error

  public function copyNewMediaToSongs($mysqli) {

   shell_exec('sudo sh /var/www/html/musicbox/include/');
   return 1;


What Logcat shows me ...

08-09 04:16:01.420 2812-2979/com.ruecgames.sengproject.musicbox I/System.out: [ ] 0x85ca2597 NORMAL 18admin_control 08-09 04:16:09.008 2812-2812/com.ruecgames.sengproject.musicbox E/getConfig: Connection Error: null

No static field INSTANCE of type Lorg/apache/http/message/BasicHeaderValueFormatter

Error log;

Process: com.project.publiko, PID: 27061
                                                                 java.lang.NoSuchFieldError: No static field INSTANCE of type Lorg/apache/http/message/BasicHeaderValueFormatter; in class Lorg/apache/http/message/BasicHeaderValueFormatter; or its superclasses (declaration of 'org.apache.http.message.BasicHeaderValueFormatter' appears in /system/framework/ext.jar)
                                                                     at org.apache.http.entity.ContentType.toString(
                                                                     at org.apache.http.entity.mime.MultipartFormEntity.<init>(
                                                                     at org.apache.http.entity.mime.MultipartEntityBuilder.buildEntity(
                                                                     at org.apache.http.entity.mime.MultipartEntity.getEntity(
                                                                     at org.apache.http.entity.mime.MultipartEntity.writeTo(
                                                                     at com.project.publiko.CustomMultipartRequest.getBody(

Tried all the possible ways, not got the proper solution since last 5 hours stuck on this error tried all google answers also which library should i compile????

*Refer ErrorLine

** Gradle

 useLibrary  'org.apache.http.legacy'}


public class CustomMultipartRequest extends Request<String> {
private Response.Listener<String> mListener = null;
private Response.ErrorListener mEListener;

private long cacheTimeToLive = 0;
private Map<String, String> header;
MultipartEntity entity;

public Map<String, String> getHeaders() throws AuthFailureError {
    // you can add your custom headers here
    HashMap<String, String> headers = new HashMap<>();

    return headers;

public CustomMultipartRequest(String url, Response.ErrorListener eListener, Response.Listener<String> rListener, MultipartEntity entity) {
    super(Method.POST, url, eListener);
    mListener = rListener;
    mEListener = eListener;
    this.entity = entity;

public String getBodyContentType() {
    return entity.getContentType().getValue();

public byte[] getBody() throws AuthFailureError {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    try {
     **Error Line**   entity.writeTo(bos);
        String entityContentAsString = new String(bos.toByteArray());
        Log.e("volley", entityContentAsString);
    } catch (IOException e) {
        VolleyLog.e("IOException writing to ByteArrayOutputStream");
    return bos.toByteArray();

protected void deliverResponse(String response) {
    Log.d("DEBUG::Volley", response.toString());
    System.out.println("VolleyQueue: Response Delivered for " + getTag()
            + " (" + getSequence() + ")");
    // TODO Auto-generated method stub

protected Response<String> parseNetworkResponse(NetworkResponse response) {
    // TODO Auto-generated method stub
    try {

        // Volley does not handle null properly, so implement null response
        // check
        if ( == 0) {
            byte[] responseData = "{}".getBytes("UTF8");
            response = new NetworkResponse(response.statusCode,
                    responseData, response.headers, response.notModified);

        String jsonString = new String(,
        return Response.success(jsonString,
    } catch (UnsupportedEncodingException e) {
        System.out.println("VolleyQueue: Encoding Error for " + getTag()
                + " (" + getSequence() + ")");
        return Response.error(new ParseError(e));

public Cache.Entry parseIgnoreCacheHeaders(NetworkResponse response) {
    long now = System.currentTimeMillis();

    Map<String, String> headers = response.headers;
    long serverDate = 0;
    String serverEtag;
    String headerValue;

    headerValue = headers.get("Date");
    if (headerValue != null) {
        serverDate = HttpHeaderParser.parseDateAsEpoch(headerValue);
    serverEtag = headers.get("ETag");

    final long cacheHitButRefreshed = 15 * 60 * 1000; //Fifteen Minutes
    final long cacheExpired = cacheTimeToLive;
    final long softExpire = now + cacheHitButRefreshed;
    final long ttl = now + cacheExpired;

    Cache.Entry entry = new Cache.Entry(); =;
    entry.etag = serverEtag;
    entry.softTtl = softExpire;
    entry.ttl = ttl;
    entry.serverDate = serverDate;
    entry.responseHeaders = headers;

    return entry;

public void deliverError(VolleyError error) {




call to the class

   CustomMultipartRequest req = new CustomMultipartRequest(URL,  //url where you want to send the multipart request
                 elistener, //instance of onErrorResponse Listener
                 rlistener,  //instance of onResponse Listener
        RequestQueue rq = Volley.newRequestQueue(context);

thanks in advance ;)

Android volley https with self-signed ssl certificate and strict client auth

Can someone point me to the right direction, how to do self-signed ssl connection with client certificate and key in Volley, when apache server accepts connections, only when the client self-signed SSL certificate and key is passed? As i get, i need to pass two certificates, one is client cert, and one is CA? Or maybe i should pass only client certificate, so apache accepts connection? How should i do that, so the library won't pass an error like "No peer certificate"? When i go to the site in a browser, i get an error that no certificate passed, so when i connect with cURL client.crt and client.key, i am able to connect.

The apache is configured with server.crt, server.key and ca.crt.

Thank you.

How to amend my code in my JSON functions java class from using apache imports in SDK 22 to Volley using SDK 23 in Android Studio

In SDK API 22 the code works. However now I want to add other classes to this project that require SDK API23. When I amend the android and dependancies in build.gradle to compile SDK version 23 one java class shows an error under all the apache code.

I know that using apache in Android Studio has been deprecated from API23.

Do I now have to completely rewrite this class to use volley or is there an easier way? I just want some advice on the best way forward at this point.

Other classes I have used in this project use the Volley libruary included as a dependancy to perform POST functions with the server and show no errors in either SDK version.

    package com.david.jobz;

import android.util.Log;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;


public class JSONfunctions {

    public static JSONObject getJSONfromURL(String url) {
        InputStream is = null;
        String result = "";
        JSONObject jArray = null;

        // Download JSON data from URL
        try {
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(url);
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
        is = entity.getContent();

    } catch (Exception e) {
        Log.e("log_tag", "Error in http connection " + e.toString());

    // Convert response to string
    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        result = sb.toString();
    } catch (Exception e) {
        Log.e("log_tag", "Error converting result " + e.toString());

    try {

        jArray = new JSONObject(result);
    } catch (JSONException e) {
        Log.e("log_tag", "Error parsing data " + e.toString());


        return jArray;


    buildscript {
    repositories {
        maven { url '' }

    dependencies {
        classpath ''
apply plugin: ''
apply plugin: 'io.fabric'

repositories {
    maven { url '' }

android {
    compileSdkVersion 22
    buildToolsVersion '23.0.2'

    defaultConfig {
        applicationId "com.david.jobz"
        minSdkVersion 22
        targetSdkVersion 22
        versionCode 1
        versionName "1.0"
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), ''
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_7
        targetCompatibility JavaVersion.VERSION_1_7

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    testCompile 'junit:junit:4.12'
    compile ''
    compile ''
    compile ''
    compile 'com.mcxiaoke.volley:library:1.0.18'
    compile('[email protected]') {
        transitive = true;

Apache HTTP Client Removal from API23, will that have an effect on Volley?

As we have known that Apache HTTP Client removed in API 23

Apache HTTP Client Removal

However, Volley library currently still uses Apache's library such as

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.impl.cookie.DateUtils;

And I have tested 2 projects: one with compileSdkVersion 22, the other with compileSdkVersion 23, got 2 screenshots:

compileSdkVersion 22

enter image description here

compileSdkVersion 23

enter image description here

I have 2 questions:

  1. Of course, API23 projects using Volley still work successfully. However, I don't understand how they use the Apache's library at runtime, do they find in API22 or lower instead?
  2. Moreover, I wonder if in the near future, will Volley be upgraded so that no longer uses Apache's library? If not, will my current projects still work in the future when Apache's library completely removed and not supported?

Perhaps my English is not so clear, however, hope that you understand my question.

Any explanation will be appreciated.