在执行下面完整代码的行while ((line = br.readLine()) != null) {
}中的BufferedReader.readLine()时,我遇到了IOException。 Exception.getMessage()
返回 BufferedInputStream已关闭。
它只发生在HTC设备中,当我使用索尼爱立信XPERIA时,它不会发生。
我的完整代码:
public static String downloadString(String url) throws MalformedURLException, IOException {
InputStream is = downloadStream(url);
//Convert stream into String
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(is), 4096);
StringBuilder sb = new StringBuilder();
while ((line = br.readLine()) != null) {
sb.append(line);
}
br.close();
return sb.toString();
}
public static InputStream downloadStream(String url) throws MalformedURLException, IOException {
return connection(url).getInputStream();
}
private static HttpURLConnection connection(String s_url) throws MalformedURLException, IOException {
URL url = new URL(s_url);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.connect();
return urlConnection;
}
如何制作适用于每个设备的更好的downloadString方法?
提前致谢。非常感谢您的回答
答案 0 :(得分:1)
试一试 -
public static String getContent(String url) throws Exception {
return(new Scanner(new URL(url).openConnection().getInputStream()).useDelimiter("/z").next());
}
答案 1 :(得分:1)
尝试使用HttpGet来处理http GET连接(和HttpPost来处理http POST)
并确保在不需要时始终关闭流。
这里使用httpget从服务器获取String的简单代码:
private void executeRequest(HttpUriRequest request)
{
HttpClient client = new DefaultHttpClient();
HttpResponse httpResponse;
try {
httpResponse = client.execute(request);
responseCode = httpResponse.getStatusLine().getStatusCode();
message = httpResponse.getStatusLine().getReasonPhrase();
System.out.println(responseCode + ":" +message);
HttpEntity entity = httpResponse.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
response = convertStreamToString(instream);
// Closing the input stream will trigger connection release
instream.close();
}
} catch (ClientProtocolException e) {
client.getConnectionManager().shutdown();
Toast.makeText(null, "Error", Toast.LENGTH_LONG);
} catch (IOException e) {
client.getConnectionManager().shutdown();
Toast.makeText(null, "Error", Toast.LENGTH_LONG);
} catch (OAuthMessageSignerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (OAuthExpectationFailedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (OAuthCommunicationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
你可以这样调用这个函数:
HttpGet request = new HttpGet(url);
executeRequest(请求);