問題是編輯,以下是額外的代碼,並應工作(我的十六進制轉換碼):
//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);
}
你需要的原始字節轉換爲十六進制字符或什麼他們正在使用的URL友好的編碼。 Base32或Base64編碼是可能的,但直接的十六進制字符是最常見的。該字符串不需要URLEncoder,因爲它不應包含任何需要URL編碼爲%NN格式的字符。
下面將轉換字節的哈希(SHA-1,MD5SUM等)爲十六進制字符串:
/** 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);
}
這段代碼是相當優化,速度快,我用它爲自己的SHA -1字節編碼。請注意,您可能需要使用String.toLowerCase()方法將大寫字母轉換爲小寫字母,具體取決於服務器接受的格式。
我已經編輯我的帖子,包括新的代碼來回答你的問題,編輯。 – BobMcGee 2009-06-19 21:02:11