java - Speedup image upload using Httpurlconnection -
is there way speedup process of uploading image web server. app developing takes long upload image. code works , know able upload image server successfully. based code off of tutorial found here.
public string uploadfile(string apipath, string filepath, string type) { string path = ""; string result = ""; switch (type) { case "m": path = "merchant/" + apipath; break; case "c": path = "customer/" + apipath; break; } log.i(apisecuritymanager.class.getsimplename(), m_token); string href = "http://tysomapi.fr3dom.net/" + path + "?token=" + m_token; log.i(apisecuritymanager.class.getsimplename(), href); try { string myip = getip(); string charset = "utf-8"; file file = new file(filepath); printwriter writer; outputstream outputstream; url url = new url(href); httpurlconnection conn = (httpurlconnection) url.openconnection(); conn.setrequestproperty("user-agent", "java"); conn.setdoinput(true); conn.setusecaches(false); conn.setrequestmethod("post"); conn.setrequestproperty("image", file.getname()); conn.setrequestproperty("content-type", "multipart/form-data; boundary = " + boundary); conn.setrequestproperty("x-forwarded-for", myip); conn.setdooutput(true); outputstream = conn.getoutputstream(); writer = new printwriter(new outputstreamwriter(outputstream, charset), true); writer.append(twohyphens + boundary + line_feed); writer.append("content-disposition: form-data; name=\"image\"; filename=\"" + file.getname() + "\"" + line_feed); writer.append("contenttype: image/peg" + line_feed); writer.append(twohyphens + boundary + line_feed); writer.flush(); writer.append(twohyphens + boundary + line_feed); writer.append("content-transfer-encoding: binary").append(line_feed); writer.append(line_feed); writer.flush(); fileinputstream inputstream = new fileinputstream(file); byte[] buffer = new byte[4096]; int bytesread = -1; while ((bytesread = inputstream.read(buffer)) != -1) { outputstream.write(buffer, 0, bytesread); } outputstream.flush(); inputstream.close(); writer.append(line_feed); writer.flush(); writer.append(line_feed); writer.append(twohyphens + boundary + twohyphens + line_feed); writer.close(); log.i(getclass().getsimplename(), "response code: " + conn.getresponsecode()); if (conn.getresponsecode() != httpurlconnection.http_ok) { throw new runtimeexception("failed : http error code : " + conn.getresponsecode()); } bufferedreader br = new bufferedreader(new inputstreamreader( (conn.getinputstream()))); string output; while ((output = br.readline()) != null) { result = result + output; } conn.disconnect(); } catch ( malformedurlexception e ) { e.printstacktrace(); } catch ( ioexception e ) { e.printstacktrace(); } return result; }
use library:
https://github.com/gotev/android-upload-service/wiki
it automatically handle url connections, failures & retries.
Comments
Post a Comment