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;
            buildMultipartEntity();
            mHttpEntity = mEntity.build();
        }

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

        @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){
                if (DEBUG) Log.d(TAG, "IOException writing to ByteArrayOutputStream");
            }
            return bos.toByteArray();
        }

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

        @Override
        protected void deliverResponse(String response){
          mListener.onResponse(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 manage.py 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(com.android.volley.Request.Method.POST,
            AppConfig.URL_SERVER, new Response.Listener<String>() {



        @Override
        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 {

                    Toast.makeText(context,
                            "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();


                e.printStackTrace();
            }
        }
    }, new Response.ErrorListener() {
        @Override
        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);


}

Listener.php

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

    $db_functions->copyNewMediaToSongs($mysqli);

     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/findmp3.sh');
   return 1;

   }

What Logcat shows me ...

08-09 04:16:01.420 2812-2979/com.ruecgames.sengproject.musicbox I/System.out: [ ] http://192.168.2.123/musicbox/include/Listener.php 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(ContentType.java:153)
                                                                     at org.apache.http.entity.mime.MultipartFormEntity.<init>(MultipartFormEntity.java:56)
                                                                     at org.apache.http.entity.mime.MultipartEntityBuilder.buildEntity(MultipartEntityBuilder.java:236)
                                                                     at org.apache.http.entity.mime.MultipartEntity.getEntity(MultipartEntity.java:119)
                                                                     at org.apache.http.entity.mime.MultipartEntity.writeTo(MultipartEntity.java:180)
                                                                     at com.project.publiko.CustomMultipartRequest.getBody(CustomMultipartRequest.java:57)
                                                                     at com.android.volley.toolbox.HurlStack.addBodyIfExists(HurlStack.java:236)
                                                                     at com.android.volley.toolbox.HurlStack.setConnectionParametersForRequest(HurlStack.java:210)
                                                                     at com.android.volley.toolbox.HurlStack.performRequest(HurlStack.java:106)
                                                                     at com.android.volley.toolbox.BasicNetwork.performRequest(BasicNetwork.java:93)
                                                                     at com.android.volley.NetworkDispatcher.run(NetworkDispatcher.java:110)

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

android{
 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;

@Override
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;
}

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

@Override
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();
}

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

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

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

        String jsonString = new String(response.data,
                HttpHeaderParser.parseCharset(response.headers));
        return Response.success(jsonString,
                parseIgnoreCacheHeaders(response));
    } 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.data = response.data;
    entry.etag = serverEtag;
    entry.softTtl = softExpire;
    entry.ttl = ttl;
    entry.serverDate = serverDate;
    entry.responseHeaders = headers;

    return entry;
}

@Override
public void deliverError(VolleyError error) {

    super.deliverError(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
                entityBuilder);
        req.setShouldCache(false);
        RequestQueue rq = Volley.newRequestQueue(context);
        rq.add(req);

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.

JSONfunctions.java

    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;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

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");
        }
        is.close();
        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;
    }
}

build.gradle

    buildscript {
    repositories {
        maven { url 'https://maven.fabric.io/public' }
    }

    dependencies {
        classpath 'io.fabric.tools:gradle:1.+'
    }
}
apply plugin: 'com.android.application'
apply plugin: 'io.fabric'

repositories {
    maven { url 'https://maven.fabric.io/public' }
}


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'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_7
        targetCompatibility JavaVersion.VERSION_1_7
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:22.2.0'
    compile 'com.android.support:support-v4:22.2.0'
    compile 'com.android.support:design:22.2.0'
    compile 'com.mcxiaoke.volley:library:1.0.18'
    compile('com.crashlytics.sdk.android:crashlytics:[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.