【问题标题】:Downloading file via POST: using setDoInput() and setDoOutput() at the same time通过 POST 下载文件:同时使用 setDoInput() 和 setDoOutput()
【发布时间】:2014-08-08 12:34:27
【问题描述】:

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

【问题讨论】:

    标签: java android https http-post illegalstateexception


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-16
      • 2012-11-11
      • 1970-01-01
      • 2023-03-19
      • 1970-01-01
      • 2022-12-17
      相关资源
      最近更新 更多