私は、HTTP GET 要求を使用してサーバーと通信する J2ME アプリケーションに取り組んでいます。URL エンコードされたパラメーターを生成する方法は既にあります。
現在の形式では、空の文字列に対応できません。私が見た他のコード スニペットにもこの欠点があります。それらはすべて、文字列引数の個々の文字を比較することに依存しているためです。以前、この空の文字のジレンマに関連する質問をしました
編集:
サーバー (Play 1.0) へのリクエストは次の形式です。
http://server.com/setName/firstname/othername/lastname
パラメータを null にすることはできないため、http:server.com/setname/firstname//lastname は無効です
パラメータはjsonオブジェクトから取得されます.現在、私が持っているurlエンコーディング方法は、抽出されたすべてのパラメータを正しくエンコードし、変換できない文字をそのまま残します.「Jo e」のような文字列内のスペースとスペース文字自体はそれぞれ Jo%20e および %20 としてエンコードされます。JSON オブジェクト
{ "firstname":"joe"
"othername":""
"lastname":"bloggs"
}
ただし、 othername パラメーターは空の文字列であり、私の方法ではそのまま残されるため、無効な 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));
}