我有一个symfony webservice,将数据库表的内容作为json返回。
此代码直接来自Android HttpUrlConnection tutorials本身。
更短的json响应能够完美地工作
org.json.JSONException:在...的字符50000处的未终止字符串{我的jason继续一段时间并被terminated终止我假设的代表空char []部分
这是它出错的地方,读者没有正确填充缓冲区
// Reads an InputStream and converts it to a String.
public String readIt(InputStream stream, int len) throws IOException {
Reader reader = new InputStreamReader(stream, "UTF-8");
char[] buffer = new char[len];
reader.read(buffer);
return new String(buffer);
}
HttpUrlConnection调用代码:
/*
Given a URL, establishes an HttpUrlConnection and retrieves
the web page content as a InputStream, which it returns as
a string.
*/
private String downloadUrl(String myurl) throws IOException {
InputStream inputStream = null;
/*
Only display the first 500 characters of the retrieved
web page content.
*/
int len = 5000;
String result = "[]";
try {
System.out.print("TRYING TO OPEN: " + myurl + "\n");
URL url = new URL(myurl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setReadTimeout(30000 /* milliseconds */);
connection.setConnectTimeout(30000 /* milliseconds */);
connection.setRequestMethod("POST");
connection.setDoInput(true);
// Starts the query
connection.connect();
int response = connection.getResponseCode();
Log.d("HTTP CONNECTION :", "The response is: " + response);
inputStream = connection.getInputStream();
// Convert the InputStream into a string
result = readIt(inputStream, len);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (inputStream != null) {
inputStream.close();
}
}
return result;
}
我遇到的大多数其他SO答案都提到现在已弃用的代码,感谢您阅读。