Android HTTP POST file upload not working with HttpUrlConnection -
i trying upload file server via http post device. have 2 method upload1 , upload2.
upload1 uses httppost class , works, bigger files throws out of memory exception.
upload2 uses httpurlconnection , not work. (i bad request message server.) want upload2 work, because uses stream send data , throws no out of memory exception. looked @ packages in wireshark, headers seems same, length upload1 380, upload2 94. problem?
private void upload1(file file) { try { httpclient httpclient = new defaulthttpclient(); httppost httppost = new httppost(url + "?recname=" + filename); // /////////////////////////////////////// string lineend = "\r\n"; string twohyphens = "--"; string boundary = "---------------------------this boundary"; bytearrayoutputstream baos = new bytearrayoutputstream(); dataoutputstream dos = new dataoutputstream(baos); fileinputstream fin = new fileinputstream(file); byte audiodata[] = new byte[(int) file.length()]; fin.read(audiodata); fin.close(); // send binary file dos.writebytes(twohyphens + boundary + lineend); dos.writebytes("content-disposition: form-data; name=\"file\";filename=\"" + filename + "\"" + lineend); dos.writebytes("content-type: audio/mp4" + lineend); dos.writebytes("content-transfer-encoding: binary" + lineend); dos.writebytes(lineend); dos.write(audiodata); dos.writebytes(lineend); dos.writebytes(twohyphens + boundary + twohyphens + lineend); dos.flush(); dos.close(); bytearrayinputstream content = new bytearrayinputstream( baos.tobytearray()); basichttpentity entity = new basichttpentity(); entity.setcontent(content); entity.setcontentlength(baos.tobytearray().length); httppost.addheader("content-type", "multipart/form-data; boundary=" + boundary); httppost.setentity(entity); // ////////////////////////////////// httpresponse response = httpclient.execute(httppost); bufferedreader reader = new bufferedreader(new inputstreamreader( response.getentity().getcontent(), "utf-8")); stringbuilder builder = new stringbuilder(); (string line = null; (line = reader.readline()) != null;) { builder.append(line).append("\n"); } reader.close(); message = builder.tostring(); system.out.println(message); } catch (unknownhostexception e) { message = "error! server unreachable. check internet connection!"; } catch (exception e) { message = "error: " + e.tostring(); } }
/////////////////////////////////////////////////////////////////////////////////////////
private void upload2(file file) { httpurlconnection connection = null; string pathtoourfile = file.getpath(); string lineend = "\r\n"; string twohyphens = "--"; string boundary = "---------------------------this boundary"; int bytesread, bytesavailable, buffersize; byte[] buffer; int maxbuffersize = 1 * 1024 * 1024; try { fileinputstream = new fileinputstream(new file(pathtoourfile)); url server_url = new url(url+ "?recname=" + filename); connection = (httpurlconnection) server_url.openconnection(); // allow inputs & outputs connection.setdoinput(true); connection.setdooutput(true); connection.setusecaches(false); // enable post method connection.setrequestmethod("post"); string bodyheader = twohyphens + boundary + lineend + "content-disposition: form-data; name=\"file\";filename=\"" + filename + "\"" + lineend + "content-type: audio/mp4" + lineend + "content-transfer-encoding: binary" + lineend + lineend + twohyphens + boundary + twohyphens ; byte[] bodyheaderaray = bodyheader.getbytes(); connection.setrequestproperty("connection", "keep-alive"); connection.setrequestproperty("content-type", "multipart/form-data;boundary=" + boundary); connection.setrequestproperty("expect", "100-continue"); // content-length int bodyheadersize = (int) file.length() + bodyheaderaray.length; system.out.println("body header size: " + bodyheadersize); // connection.setfixedlengthstreamingmode(bodyheadersize); outputstream = new dataoutputstream(connection.getoutputstream()); outputstream.writebytes(twohyphens + boundary + lineend); outputstream .writebytes("content-disposition: form-data; name=\"file\";filename=\"" + filename + "\""); outputstream.writebytes(lineend); outputstream.writebytes("content-type: audio/mp4" + lineend); outputstream.writebytes("content-transfer-encoding: binary" + lineend); bytesavailable = fileinputstream.available(); buffersize = math.min(bytesavailable, maxbuffersize); buffer = new byte[buffersize]; // read file bytesread = fileinputstream.read(buffer, 0, buffersize); while (bytesread > 0) { outputstream.write(buffer, 0, buffersize); bytesavailable = fileinputstream.available(); buffersize = math.min(bytesavailable, maxbuffersize); bytesread = fileinputstream.read(buffer, 0, buffersize); } outputstream.writebytes(lineend); outputstream.writebytes(twohyphens + boundary + twohyphens + lineend); fileinputstream.close(); outputstream.flush(); outputstream.close(); // responses server (code , message) int serverresponsecode = connection.getresponsecode(); string serverresponsemessage = connection.getresponsemessage(); message = serverresponsemessage; } catch (exception ex) { system.out.println(ex); } }
according problems getting upload files. should use multipart mechanism upload files server.
httpclient-4.1.jar httpcore-4.1.jar httpmime-4.1.jar apache-mime4j-0.6.1.jar
for need add couple of libraries project , use http connection , file data.
private boolean uploadfile(file mfile) { boolean success = true; string filename = mfile.getname(); multipartentity data_to_send = new multipartentity( httpmultipartmode.browser_compatible); try { data_to_send.addpart( "name", new stringbody( filename.substring(filename.lastindexof("/") + 1))); data_to_send.addpart("filedata", new filebody(mfile)); } catch (unsupportedencodingexception e) { e.printstacktrace(); } try { string responsedata = consumewebservice.sendrequest(data_to_send, global.base_url + serviceurl); if (textutils.isempty(responsedata) || responsedata.equals(consumewebservice.error_code)) { success = false; } } catch (exception e) { success = false; e.printstacktrace(); } return success; } public static string sendrequest(multipartentity data, string url) { string response = ""; response = postdata(url, data); return response; } private static string postdata(string url, multipartentity data) { string strresponse = ""; try { log.d(global.tag, "post url " + url); httppost httppost = new httppost(url); httppost.setentity(data); strresponse = httpclient.execute(httppost, new basicresponsehandler()); } catch (unsupportedencodingexception e) { strresponse = error_code; e.printstacktrace(); } catch (clientprotocolexception e) { strresponse = error_code; e.printstacktrace(); } catch (ioexception e) { strresponse = error_code; e.printstacktrace(); } return strresponse; }
Comments
Post a Comment