Question a été modifiée alors que je répondais, suivant est un code supplémentaire et devrait fonctionner (avec mon code de conversion hexadécimal):
//Inefficient, but functional, does not test if input is in hex charset, so somewhat unsafe
//NOT tested, but should be functional
public static String encodeURL(String hexString) throws Exception {
if(hexString==null || hexString.isEmpty()){
return "";
}
if(hexString.length()%2 != 0){
throw new Exception("String is not hex, length NOT divisible by 2: "+hexString);
}
int len = hexString.length();
char[] output = new char[len+len/2];
int i=0;
int j=0;
while(i<len){
output[j++]='%';
output[j++]=hexString.charAt(i++);
output[j++]=hexString.charAt(i++);
}
return new String(output);
}
Vous aurez besoin de convertir les octets bruts en caractères hexadécimaux ou autre Encodage URL-friendly qu'ils utilisent. Les encodages Base32 ou Base64 sont possibles, mais les caractères hexadécimaux droits sont les plus courants. URLEncoder n'est pas nécessaire pour cette chaîne, car elle ne doit contenir aucun caractère nécessitant le codage de l'URL au format% NN.
Le ci-dessous vous permet de convertir octets pour un hachage (SHA-1, MD5SUM, etc.) à une chaîne hexadécimale:
/** Lookup table: character for a half-byte */
static final char[] CHAR_FOR_BYTE = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
/** Encode byte data as a hex string... hex chars are UPPERCASE*/
public static String encode(byte[] data){
if(data == null || data.length==0){
return "";
}
char[] store = new char[data.length*2];
for(int i=0; i<data.length; i++){
final int val = (data[i]&0xFF);
final int charLoc=i<<1;
store[charLoc]=CHAR_FOR_BYTE[val>>>4];
store[charLoc+1]=CHAR_FOR_BYTE[val&0x0F];
}
return new String(store);
}
Ce code est assez optimisé et rapide, et je l'utilise pour mon propre SHA -1 octet d'encodage. Notez que vous devrez peut-être convertir les majuscules en minuscules avec la méthode String.toLowerCase(), selon la forme acceptée par le serveur.
J'ai édité mon post pour inclure un nouveau code pour répondre à votre question éditée. – BobMcGee