通过POST下载文件:同时使用setDoInput()和setDoOutput()

时间:2014-06-18 09:21:22

标签: java android https http-post illegalstateexception

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

1 个答案:

答案 0 :(得分:1)

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