我正在尝试通过Android上的POST下载文件,检查下载进度并将其保存到SD卡上的文件中。这是我AsyncTask
的代码:
class DownloadFileAsync extends AsyncTask<String, String, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(DIALOG_DOWNLOAD_PROGRESS);
}
@Override
protected String doInBackground(String... arg) {
try {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("id", arg[0]));
StringBuilder result = new StringBuilder();
boolean first = true;
for (NameValuePair pair : params) {
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(pair.getName(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(pair.getValue(), "UTF-8"));
}
byte[] postDataBytes = result.toString().getBytes("UTF-8");
URL url = new URL(DOWNLOAD_URL);
HttpURLConnection conn = (HttpURLConnection) url
.openConnection();
conn.setRequestMethod("POST");
conn.setReadTimeout(10000);
conn.setRequestProperty("Content-Length",
String.valueOf(postDataBytes.length));
conn.setConnectTimeout(15000);
conn.setDoOutput(true);
conn.getOutputStream().write(postDataBytes);
int lenghtOfFile = conn.getContentLength();
FileOutputStream f = new FileOutputStream(new File(rootDir
+ "/__test/", fileName));
conn.setDoInput(true);
InputStream in = conn.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
long total = 0;
while ((len1 = in.read(buffer)) > 0) {
total += len1;
publishProgress("" + (int) ((total * 100) / lenghtOfFile));
f.write(buffer, 0, len1);
}
f.close();
conn.connect();
} catch (Exception e) {
e.printStackTrace();
DebugLog.e(TAG, e.getMessage());
}
return null;
}
protected void onProgressUpdate(String... progress) {
DebugLog.d(TAG, progress[0]);
mProgressDialog.setProgress(Integer.parseInt(progress[0]));
}
@Override
protected void onPostExecute(String unused) {
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
}
}
public void checkAndCreateDirectory(String dirName) {
File new_dir = new File(rootDir + dirName);
if (!new_dir.exists()) {
new_dir.mkdirs();
}
}
问题在于,当我尝试同时使用setDoInput()
和setDoOutput()
方法时,出现java.lang.IllegalStateException: Already connected
错误。我该如何解决?
答案 0 :(得分:1)
在conn.setDoInput(true)
之前同时执行conn.setDoOutput(true)
和conn.getOutputStream()
。