java - Downloading file via POST: using setDoInput() and setDoOutput() at the same time -
i trying download file via post on android, check progress of download , save file on sd card. here code of asynctask:
class downloadfileasync extends asynctask<string, string, string> { @override protected void onpreexecute() { super.onpreexecute(); showdialog(dialog_download_progress); } @override protected string doinbackground(string... arg) { seek { list<namevaluepair> params = new arraylist<namevaluepair>(); params.add(new basicnamevaluepair("id", arg[0])); stringbuilder result = new stringbuilder(); boolean first = true; (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(); } grab (exception e) { e.printstacktrace(); debuglog.e(tag, e.getmessage()); } homecoming 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(); } } the problem when seek utilize setdoinput() , setdooutput() methods @ same time, java.lang.illegalstateexception: connected error. how can solve it?
do both conn.setdoinput(true) , conn.setdooutput(true) before conn.getoutputstream().
java android https http-post illegalstateexception
No comments:
Post a Comment