我不是专业开发的android。我想从我的服务器下载一个JSON对象,但只有我能找到的代码是这样的:
private String downloadUrl(String myurl) throws IOException {
InputStream is = null;
// Only display the first 500 characters of the retrieved
// web page content.
int len = 500;
try {
URL url = new URL(myurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
// Starts the query
conn.connect();
int response = conn.getResponseCode();
Log.d("ServerConnection", "The response is: " + response);
is = conn.getInputStream();;
//is.
// Convert the InputStream into a string
String contentAsString = readIt(is, len);
return contentAsString;
// Makes sure that the InputStream is closed after the app is
// finished using it.
} catch (MalformedURLException e) {
//
return "error";
} catch (IOException e) {
//
return "error";
} finally {
if (is != null) {
is.close();
}
}
}
它工作正常,我无法理解。但它有int len = 500
,我返回的json被裁剪为500个字符。我尝试过更改为一个很好的数字,但它最后会添加空格。如何知道InputSteam包含的字符串的大小?
由于
答案 0 :(得分:1)
您可以检查回复的Content-Length标头值:
Map<String, List<String>> headers = connection.getHeaderFields();
for (Entry<String, List<String>> header : headers.entrySet()) {
if(header.getKey().equals("Content-Legth")){
len=Integer.parseInt(header.getValue());
}
}
或者你可以在这样的缓冲读卡器中做出回应:
InputStream is = connection.getInputStream();
InputStreamReader reader = new InputStreamReader(is);
StringBuilder builder = new StringBuilder();
int c = 0;
while ((c = reader.read()) != -1) {
builder.append((char) c);
}
答案 1 :(得分:0)
Yout可以使用Apache Commons IO IOUtils.toString将InputStream转换为String或使用Gson直接从输入流中读取对象:
return gson.fromJson(new InputStreamReader(inputStream), YourType.class);