我正在尝试将数据保存到一个尚未在线存在的文本文件中,但我的urlConnection.getResponseCode()
正在返回404.我可以从具有相似网址的文件中读取,所以我很确定网址是是的,但我以前从未写过在线文件。
private class SaveFile extends AsyncTask<String, Void, String> {
private String scheme = "http";
private String authority = "172.16.0.45";
private String path1 = "PrivateFile";
private String path2 = "SavedInstances";
protected void onPreExecute() {
}
protected String doInBackground(String...params) {
String result = null;
String filename = params[0] + ".txt";
String location = params[1];
OutputStream outStream = null;
HttpURLConnection urlConnection = null;
try {
// Save online as opposed to internal storage
if (location.equals("on")) {
Uri.Builder builder = new Uri.Builder();
builder.scheme(scheme);
builder.authority(authority);
builder.appendPath(path1);
builder.appendPath(path2);
builder.appendPath(filename);
String _url = builder.build().toString();
URL url = new URL(_url);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoOutput(true);
urlConnection.setRequestMethod("POST");
if (urlConnection.getResponseCode() != 200) // Runs as true
throw new IOException(Integer.toString(urlConnection.getResponseCode()));
else {
outStream = urlConnection.getOutputStream();
}
} else if (location.equals("in")) {// Saving to internal
File file = new File(getFilesDir(), filename);
outStream = new FileOutputStream(file);
}
// Writing the file
PrintWriter writer = new PrintWriter(outStream);
writer.println(utils.size());
writer.println(trans.size());
writer.println(cables.size());
for (int i = 0; i < utils.size(); i++)
writer.println(utils.get(i).getValues());
for (int i = 0; i < trans.size(); i++)
writer.println(trans.get(i).getValues());
for (int i = 0; i < cables.size(); i++)
writer.println(cables.get(i).getValues());
writer.close();
outStream.close();
if (urlConnection != null)
urlConnection.disconnect();
result = "Save Successful";
} catch (FileNotFoundException e) {
System.out.println(e.getMessage());
} catch (MalformedURLException e) {
System.out.println(e.getMessage());
} catch (IOException e) {
result = e.getMessage();// 404
System.out.println(e.getMessage());
}
return result;
}
protected void onPostExecute(String result) {
Toast.makeText(getApplicationContext(),result,Toast.LENGTH_SHORT).show();
}
}
当我使用getResponseMessage()发送异常时,消息“未找到”。为了让这种联系起作用,我错过了什么?