哎,java学的不精各种百度copy代码,结果弄出各种奇葩问题。这不百度了一个HttpURLConnection 模拟http请求的就出问题了:
String message = "";
try {
URL url = new URL(uri);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(5 * 1000);
connection.connect();
InputStream inputStream = connection.getInputStream();
byte[] data = new byte[1024];
StringBuffer sb = new StringBuffer();
int length = 0;
while ((length = inputStream.read(data)) != -1) {
String s = new String(data, Charset.forName("utf-8"));
//Log.debug("Http.get", s);
sb.append(s);
}
message = sb.toString();
inputStream.close();
connection.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
return message;
他本来应该返回一段JSON,但是这段代码结尾总是会多出几个字符。
排除了服务器的问题后,终于发现了问题所在:
String s = new String(data,Charset.forName("utf-8"));
关键部分就是这行代码,我的缓冲区是1024,但是因为内容比较长,分了两次读完。第一次读取了1024后,第二次只读取了100就读完了。于是这1000覆盖了缓冲区的前1000字节,但是剩下的24还在缓冲区!!!
改成下面这样
String s = new String(data,0,length, Charset.forName("utf-8"));
哎,万恶之源的copy