したがって、GET を使用して Web ページを取得し、テキストをダウンロードする Android アプリでは、次のように実行します。
private InputStream OpenHttpConnection(String urlString) throws IOException {
Log.d("Networking", "InputStream called");
InputStream in = null;
int response = -1;
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
if(!(conn instanceof HttpURLConnection))
throw new IOException("Not an HTTP connection");
try {
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setConnectTimeout(10000);
httpConn.setReadTimeout(10000);
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.connect();
response = httpConn.getResponseCode();
if (response == HttpURLConnection.HTTP_OK) {
in = httpConn.getInputStream();
}
}
catch (Exception ex) {
Log.d("Networking", "" + ex.getLocalizedMessage());
throw new IOException("Error connecting");
}
return in;
}
private String DownloadText(String URL) {
int BUFFER_SIZE = 2000;
InputStream in = null;
try {
in = OpenHttpConnection(URL);
}
catch (IOException e) {
Log.d("Networking", "" + e.getLocalizedMessage());
return "";
}
InputStreamReader isr = new InputStreamReader(in);
int charRead;
String str = "";
char[] inputBuffer = new char[BUFFER_SIZE];
try {
while ((charRead = isr.read(inputBuffer))>0) {
//---convert the chars to a String---
String readString = String.copyValueOf(inputBuffer, 0, charRead);
str += readString;
inputBuffer = new char[BUFFER_SIZE]; }
in.close();
}
catch (IOException e) {
Log.d("Networking", "" + e.getLocalizedMessage());
return "";
}
return str;
}
これは、stringx = DownloadText("http://hello.com/whatever.txt") を呼び出すと、whatever.txt が存在する限り完全に機能します。
ただし、404 の場合はクラッシュします。これには驚きました。404 はまだコンテンツを返しているのではないでしょうか? 私は多くのデバッグを入れましたが、次の行を実行しているようです:
InputStreamReader isr = new InputStreamReader(in);
クラッシュする前に。この行の実行後は何もありません。このあたりで try {} catch (IOException) {} を使用してみましたが、行が例外をスローしないと表示されます。
この行がこのような問題を引き起こしている理由について、誰かが洞察を持っていますか? 私のアプリケーションはほぼ完成していますが、エラー処理が問題を引き起こしています!
どうもありがとう!