gpt4 book ai didi

java - 通过 POST : using setDoInput() and setDoOutput() at the same time 下载文件

转载 作者:行者123 更新时间:2023-11-30 02:50:23 25 4
gpt4 key购买 nike

我正在尝试在 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 : 已连接 错误。我该如何解决?

最佳答案

conn.getOutputStream() 之前同时执行 conn.setDoInput(true)conn.setDoOutput(true)

关于java - 通过 POST : using setDoInput() and setDoOutput() at the same time 下载文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24281737/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com