连接到web服务器并读取XML文件(Android)
我要做的是连接到web服务器并可以读取XML文件 例外情况是打开失败的erofs只读文件系统。 我在舱单上加了:连接到web服务器并读取XML文件(Android),android,xml,web-services,Android,Xml,Web Services,我要做的是连接到web服务器并可以读取XML文件 例外情况是打开失败的erofs只读文件系统。 我在舱单上加了: uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" 我做错了什么 public void getHTML() throws IOException { StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Buil
uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"
我做错了什么
public void getHTML() throws IOException {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
try {
URL url = new URL("http:/...");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
BufferedReader rd;
String line;
String name = "myfile.xml";
conn.setRequestMethod("GET");
rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
File file = new File(name);
if(file.exists()) {
file.delete();
file = new File(name);
}
FileWriter fw = new FileWriter(file.getName(), true);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter out = new PrintWriter(bw);
while ((line = rd.readLine()) != null) {
System.out.println(line);
fw.write(line);
fw.write("\n");
//out.println(line);
//out.flush();
}
fw.close();
out.close();
rd.close();
}
catch(Exception e){
Toast.makeText(getApplicationContext()," "+e,Toast.LENGTH_SHORT).show();
}
}
}
我做了修改,我解决了。我会发布正确的代码 公共void getHTML引发IOException{
FileOutputStream outputStream=null;
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
String fullPath = "/mnt/sdcard/";
try {
URL url = new URL("http:..");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
BufferedReader rd;
File dir = new File(fullPath.toString());
if (!dir.exists()) {
dir.mkdirs();
}
File file = new File(fullPath, "file.xml");
if(file.exists())
file.delete();
file.createNewFile();
String line;
outputStream = new FileOutputStream(file);
conn.setRequestMethod("GET");
rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String newline="\n";
while ((line = rd.readLine()) != null){
outputStream.write(line.getBytes());
outputStream.write(newline.getBytes());
outputStream.flush();
}
outputStream.close();
rd.close();
}
catch(Exception e){
Toast.makeText(getApplicationContext()," "+e,Toast.LENGTH_SHORT).show();
}
}
我们可以看看Logcat吗?首先,不鼓励使用StrictMode。你应该在一个单独的线程中进行网络操作,而不是在主线程中。。