引言
最近在使用HttpURLConnection请求到另外一个应用去获取数据,刚开始用下面的url请求数据:
String url = "http://localhost:8888/example/queryData.do?query=" +
"{\"start\":0,\"tableid\":\"EVTS\",\"rows\":10,\"token\":\"76ecc4c399e56792c5fd0905f8ffaa86\","
+ "\"order\":{},\"query\":[]}";
HttpURLConnection conn = (HttpURLConnection)new URL(url).openConnection();
conn.setDoInput(true);
conn.setDoOutput(false);
conn.setUseCaches(false);
conn.setRequestMethod("GET");
conn.setRequestProperty("Host", "www.awebsite.com");
conn.setRequestProperty("User-Agent", "Mozilla/4.0");
conn.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
conn.setRequestProperty("Accept-Language", "en-us,en;q=0.5");
conn.setRequestProperty("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7");
conn.setRequestProperty("Keep-Alive", "115");
conn.setRequestProperty("Connection", "keep-alive");
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder data = new StringBuilder();
String s = "";
while((s = br.readLine()) != null)
data.append(s);
String pageData = data.toString();
上面的请求很正常,能拿到预计的数据,但是后续url需要增加一个日期时间的入参后,出问题了,修改后的url变成了下面的这样:
String url = "http://localhost:8888/example/queryData.do?query=" +
"{\"start\":0,\"tableid\":\"EVTS\",\"rows\":10,\"token\":\"76ecc4c399e56792c5fd0905f8ffaa86\","
+ "\"order\":{},\"query\":[{"startTime":"2018-03-27 14:00:00","endTime":"2018-03-27 14:30:00"]}";
HttpURLConnection就会报下面的这种错误:
java.io.IOException: <h1>Bad Message 400</h1><pre>reason: Unknown Version</pre>
一直排查都没有发现前后有什么问题。
解决
只能上网找解决办法, stackoverflow上也有人遇到这问题:
解决的办法就是:把空格用转译符号代替。
总结
这还真是一个坑,比较隐蔽。