Apache Commons Codec with Android: could not find method

Viewed 63203

Today I tried including the apache.commons.codec package in my Android application and couldn't get it running. Android could not find method ord.apache.commons.codec.binary.* and output the following errors in DDMS

01-12 08:41:48.161: ERROR/dalvikvm(457): Could not find method org.apache.commons.codec.binary.Base64.encodeBase64URLSafeString, referenced from method com.dqminh.app.util.Util.sendRequest

01-12 08:41:48.161: WARN/dalvikvm(457): VFY: unable to resolve static method 10146: Lorg/apache/commons/codec/binary/Base64;.encodeBase64URLSafeString ([B)Ljava/lang/String;

01-12 08:41:48.161: WARN/dalvikvm(457): VFY: rejecting opcode 0x71 at 0x0004

Any clue on how to solve this problem ? Thanks a lot.

11 Answers

You can simply import the following library under Gradle dependency

dependencies {
    implementation "commons-codec:commons-codec:1.11"
}

It will work

Knowing that this is an old question, but I faced this problem recently when compiling for API Level 23, and found another solution for the problem: use guava project.

// Encoding
String encodedString = BaseEncoding.base64().encode(text.getBytes(UTF_8));
System.out.println("encodedString: " + encodedString);

// Decoding
byte[] decodedString = BaseEncoding.base64().decode(encodedString);
System.out.println("decodedString: " + new String(decodedString, UTF_8));

The guava library (18.0) was the version that I've used, and the change was smooth. The code works as expected.

Solution found in here: https://memorynotfound.com/encode-decode-base64-string-using-native-java/

This works for me:

import org.apache.commons.codec.binary.Base64;

/**
 * This is used to get the base64 from the bytes
 *
 * @param rawBytes the raw bytes
 * @return the base64 encoded string
 */
public static String getBase64String(byte[] rawBytes) {
    String base64Str = "";
    if (rawBytes!= null) {
        base64Str= new String(Base64.encodeBase64(rawBytes));
    }
    return base64Str;
}

public static byte[] getBase64DecodedString(String base64EncodedStr) {
    byte[] base64Bytes = Base64.decodeBase64(base64EncodedStr.getBytes());
    return bitmap;
}
Related