Я пытаюсь загрузить XML-файл с URL-адреса и сохранить его во внутреннем хранилище.Мой doInBackground () всегда возвращает результирующую строку в конце, но он никогда не проходит мимо getResponseCode () или, если я его удаляю, getInputStream ().Он не генерирует никаких исключений и может только возвращать "outStream made".Что мне нужно сделать, чтобы преодолеть этот барьер?
РЕДАКТИРОВАТЬ: метод вызывает IOException.Что мне нужно сделать, чтобы это исправить?
private class Updater extends AsyncTask<File, Void, String> {
private static final String _url = "http://my_working_url.xml";
protected void onPreExecute() {
}
protected String doInBackground(File... Storage) {
String result = null;
boolean madeToEnd = false;
try {
URL url = new URL(_url);
result = "made URL";
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
result = "opened connection";
urlConnection.setRequestMethod("GET");
result = "set request method";
urlConnection.setDoOutput(true);
result = "successfully connected";
FileOutputStream outStream = new FileOutputStream(Storage[0]);
result = "outStream made";
if (urlConnection.getResponseCode() != 200)
throw new Exception("Failed to connect");
else {
InputStream inStream = urlConnection.getInputStream();
result = "Made 2 streams";
int totalSize = urlConnection.getContentLength();
int downloadedSize = 0;
byte[] buffer = new byte[8500];
int bufferLength = 0;
result = "about to enter loop";
while ((bufferLength = inStream.read(buffer)) > 0) {
outStream.write(buffer, 0, bufferLength);
downloadedSize += bufferLength;
int progress = (int) (downloadedSize * 100 / totalSize);
result = "failed in loop";
}
result = "Successfully Downloaded";
madeToEnd = true;
inStream.close();
}
outStream.close();
urlConnection.disconnect();
} catch (MalformedURLException mue) {
result = "The url was not recognized as valid";
madeToEnd = true;
} catch (IOException e) {
result = "I/O Exception with openConnection()";
madeToEnd = true;
} catch (NetworkOnMainThreadException e) {
result = "Network on main thread exception";
madeToEnd = true;
} catch (Exception e) {
result = e.getMessage();
madeToEnd = true;
}
finally {
if (madeToEnd)
return result;
return "did not make it";
}
}
protected void onPostExecute(String result) {
TextView tv = findViewById(R.id.tsize_EMT);
tv.setText(result);
}
@Override
protected void onCancelled() {
TextView tv = findViewById(R.id.tsize_RMC);
tv.setText("Cancelled");
super.onCancelled();
}
}
Ключевые пункты в mainActivity Updater находятся в:
Updater updater = new Updater();
File Storage = new File(getFilesDir(),"My_internal_file" );
updater.execute(Storage);
РЕДАКТИРОВАТЬ: My LogCat
05-25 17:06:07.118 6355-6355/? I/zygote: Not late-enabling -Xcheck:jni (already on)
05-25 17:06:07.185 6355-6355/? W/zygote: Unexpected CPU variant for X86 using defaults: x86
05-25 17:06:07.438 6355-6355/com.privateinfo I/InstantRun: starting instant run server: is main process
05-25 17:06:07.567 6355-6373/com.privateinfo D/OpenGLRenderer: HWUI GL Pipeline
05-25 17:06:07.941 6355-6373/com.privateinfo I/zygote: android::hardware::configstore::V1_0::ISurfaceFlingerConfigs::hasWideColorDisplay retrieved: 0
05-25 17:06:07.941 6355-6373/com.privateinfo I/OpenGLRenderer: Initialized EGL, version 1.4
05-25 17:06:07.941 6355-6373/com.privateinfo D/OpenGLRenderer: Swap behavior 1
05-25 17:06:07.941 6355-6373/com.privateinfo W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
05-25 17:06:07.941 6355-6373/com.privateinfo D/OpenGLRenderer: Swap behavior 0
05-25 17:06:07.944 6355-6373/com.privateinfo D/EGL_emulation: eglCreateContext: 0xe6fe4ec0: maj 2 min 0 rcv 2
05-25 17:06:07.987 6355-6373/com.privateinfo D/EGL_emulation: eglMakeCurrent: 0xe6fe4ec0: ver 2 0 (tinfo 0xe6f166c0)
05-25 17:06:08.108 6355-6355/com.privateinfo I/Choreographer: Skipped 30 frames! The application may be doing too much work on its main thread.
05-25 17:06:08.137 6355-6373/com.privateinfo D/EGL_emulation: eglMakeCurrent: 0xe6fe4ec0: ver 2 0 (tinfo 0xe6f166c0)
05-25 17:06:08.201 6355-6360/com.privateinfo I/zygote: Do partial code cache collection, code=9KB, data=30KB
After code cache collection, code=9KB, data=30KB
Increasing code cache capacity to 128KB
05-25 17:06:08.202 6355-6360/com.privateinfo I/zygote: Do partial code cache collection, code=9KB, data=48KB
After code cache collection, code=9KB, data=48KB
Increasing code cache capacity to 256KB
JIT allocated 71KB for compiled code of void android.widget.TextView.<init>(android.content.Context, android.util.AttributeSet, int, int)
Compiler allocated 4MB to compile void android.widget.TextView.<init>(android.content.Context, android.util.AttributeSet, int, int)
05-25 17:06:08.284 6355-6360/com.privateinfo I/zygote: Do full code cache collection, code=97KB, data=62KB
After code cache collection, code=95KB, data=44KB
05-25 17:06:08.337 6355-6360/com.privateinfo I/zygote: Do partial code cache collection, code=95KB, data=54KB
After code cache collection, code=95KB, data=54KB
Increasing code cache capacity to 512KB
JIT allocated 72KB for compiled code of void android.widget.TextView.<init>(android.content.Context, android.util.AttributeSet, int, int)
Compiler allocated 4MB to compile void android.widget.TextView.<init>(android.content.Context, android.util.AttributeSet, int, int)
05-25 17:06:08.374 6355-6360/com.privateinfo I/zygote: JIT allocated 71KB for compiled code of void android.widget.TextView.<init>(android.content.Context, android.util.AttributeSet, int, int)
Compiler allocated 4MB to compile void android.widget.TextView.<init>(android.content.Context, android.util.AttributeSet, int, int)
05-25 17:06:08.385 6355-6360/com.privateinfo I/zygote: Do full code cache collection, code=249KB, data=94KB
After code cache collection, code=81KB, data=33KB
05-25 17:06:21.757 6355-6373/com.privateinfo D/EGL_emulation: eglMakeCurrent: 0xe6fe4ec0: ver 2 0 (tinfo 0xe6f166c0)
05-25 17:06:22.024 6355-6373/com.privateinfo I/chatty: uid=10079(com.privateinfo) RenderThread identical 29 lines
05-25 17:06:23.257 6355-6373/com.privateinfo D/EGL_emulation: eglMakeCurrent: 0xe6fe4ec0: ver 2 0 (tinfo 0xe6f166c0)
05-25 17:06:23.327 6355-6384/com.privateinfo D/NetworkSecurityConfig: No Network Security Config specified, using platform default
05-25 17:06:23.365 6355-6373/com.privateinfo D/EGL_emulation: eglMakeCurrent: 0xe6fe4ec0: ver 2 0 (tinfo 0xe6f166c0)
05-25 17:06:23.397 6355-6373/com.privateinfo I/chatty: uid=10079(com.privateinfo) RenderThread identical 4 lines
05-25 17:06:23.406 6355-6373/com.privateinfo D/EGL_emulation: eglMakeCurrent: 0xe6fe4ec0: ver 2 0 (tinfo 0xe6f166c0)
05-25 17:06:23.663 6355-6373/com.privateinfo D/EGL_emulation: eglMakeCurrent: 0xe6fe4ec0: ver 2 0 (tinfo 0xe6f166c0)
05-25 17:06:23.665 6355-6373/com.privateinfo D/OpenGLRenderer: endAllActiveAnimators on 0xdc3f9680 (MenuPopupWindow$MenuDropDownListView) with handle 0xe6f1b180
РЕДАКТИРОВАТЬ: Результирующее сообщение из IOException, выданное urlConnection.getResponseCode ():
java.net.UnknownHostException: Невозможно разрешить хост "172.16.045": Нет адреса, связанного с именем хоста
Спасибо заВаше терпение. Этот адрес хоста является частным для локального Wi-Fi.Эмулятор, который я использую, может перейти к нужному URL через свой браузер.
РЕДАКТИРОВАТЬ: приложение может загружать другие файлы из не частных сетей.Спасибо всем большое за вашу помощь;Теперь я займусь вопросом частной сети.