我有一个JSON字符串,我编码然后附加到REST URL。但问题是由于请求未经过某些特殊字符。 我的JSON字符串如下
{"empName":"Jammy","fromDateRaw":"06-11-2014 ","fromDate":"Fri May 06 00:00:00 IST 12","travelRequestNumber":"2000070293","toDate":"Sun May 06 00:00:00 IST 36","mobileNumber":"","requestedOn":"Thu Oct 16 00:52:17 IST 2014","comments":"Employee prefer the following hotel and room type:Residence Inn Dallas Addison/Quorum Drive 14975 Quorum Drive?Dallas, Texas 75254 USA"}
即使我正在对网址进行编码,但由于最后一个网址没有通过,所以#34;评论"它有3个特殊字符,它们是":/?"。如果我删除这三个字符并对此URL进行编码并将其附加到REST API,则会通过。但我需要这些角色,任何想法如何逃脱这些角色?
答案 0 :(得分:1)
您应该使用URLEncoder
类来编码您计划附加到网址的文字,例如:
String text = ""; // Insert your text here
String encoded = URLEncoder.encode(text, "UTF-8");
URLEncoder
正确转义所有特殊字符,您可以安全地将encoded
附加到网址字符串。
应用于您的字符串:
请注意,如果在Java源代码中指定了输入,则必须转义引号(使用\"
)。
String text = "{\"empName\":\"Jammy\",\"fromDateRaw\":\"06-11-2014 \",\"fromDate\":\"Fri May 06 00:00:00 IST 12\",\"travelRequestNumber\":\"2000070293\",\"toDate\":\"Sun May 06 00:00:00 IST 36\",\"mobileNumber\":\"\",\"requestedOn\":\"Thu Oct 16 00:52:17 IST 2014\",\"comments\":\"Employee prefer the following hotel and room type:Residence Inn Dallas Addison/Quorum Drive 14975 Quorum Drive?Dallas, Texas 75254 USA\"}";
String encoded = URLEncoder.encode(text, "UTF-8");
System.out.println(encoded);
输出:
%7B%22empName%22%3A%22Jammy%22%2C%22fromDateRaw%22%3A%2206-11-2014+%22%2C%22fromDate%22%3A%22Fri+May+06+00%3A00%3A00+IST+12%22%2C%22travelRequestNumber%22%3A%222000070293%22%2C%22toDate%22%3A%22Sun+May+06+00%3A00%3A00+IST+36%22%2C%22mobileNumber%22%3A%22%22%2C%22requestedOn%22%3A%22Thu+Oct+16+00%3A52%3A17+IST+2014%22%2C%22comments%22%3A%22Employee+prefer+the+following+hotel+and+room+type%3AResidence+Inn+Dallas+Addison%2FQuorum+Drive+14975+Quorum+Drive%3FDallas%2C+Texas+75254+USA%22%7D
您可以将其附加到以下网址:
URL url = new URL("http://somehost.com/something?data=" + encoded);