我正在使用HTTP GET請求與服務器進行通信的J2ME應用程序。我已經有了一種方法來生成URL編碼參數。如何在爲GET請求編碼參數時迎合空字符串?
目前的形式不能迎合空字符串,我見過的其他代碼片段也有這個缺陷,因爲它們都依賴於比較字符串參數的單個字符。 I have previously asked a question related to this empty char dilemma
編輯:
對服務器的請求(播放1.0)的形式爲
http://server.com/setName/firstname/othername/lastname
參數不能爲空,因此HTTP:server.com/setname/firstname//姓氏是無效
中的參數從一個JSON檢索object.Currently URL編碼方法我有將編碼所有所提取的參數並保留任何不能被轉換的字符。「Jo e」和空格字符本身的字符串中的空格將分別編碼爲Jo%20e和%20。 JSON對象然而
{ "firstname":"joe"
"othername":""
"lastname":"bloggs"
}
將導致無效的URL http://server.com/setname/joe//bloggs因爲中文別名參數爲空字符串,並通過我的方法原樣保留。
我可以檢查即將返回的字符串是空的,並返回一個空格字符來代替。但是我想知道這個方法是否沒有更好的修改,或者一個更強大的全新方法?
public static String urlEncode(String s) {
ByteArrayOutputStream bOut = null;
DataOutputStream dOut = null;
ByteArrayInputStream bIn = null;
StringBuffer ret = new StringBuffer();
try {
bOut=new ByteArrayOutputStream();
dOut = new DataOutputStream(bOut);
//return value
dOut.writeUTF(s);
bIn = new ByteArrayInputStream(bOut.toByteArray());
bIn.read();
bIn.read();
int c = bIn.read();
while (c >= 0) {
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '.' || c == '-' || c == '*' || c == '_') {
ret.append((char) c);
} else if (c == ' ') {
//ret.append('+');
ret.append("%20");
} else {
if (c < 128) {
appendHex(c, ret);
} else if (c < 224) {
appendHex(c, ret);
appendHex(bIn.read(), ret);
} else if (c < 240) {
appendHex(c, ret);
appendHex(bIn.read(), ret);
appendHex(bIn.read(), ret);
}
}
c = bIn.read();
}
} catch (IOException ioe) {
System.out.println("urlEncode:"+ioe);
return s;
}
return ret.toString();
}
private static void appendHex(int arg0, StringBuffer buff) {
buff.append('%');
if (arg0 < 16) {
buff.append('0');
}
buff.append(Integer.toHexString(arg0));
}
「但它沒有/不能滿足空字符串」 - 你究竟是什麼意思?空串的確切位置會導致問題,這是什麼問題?是否有異常/崩潰,或者你是否只是意想不到的行爲? – yoozer8
是否需要所有參數?有一個可選參數,還是可以有幾個? – yoozer8