Use HTTP POST and post content as Form- based file upload (type mime: multipart / form-data). This system is standard on the Internet for submitting forms and / or uploading files.
Use ex-post HTTP mode, so the size does not have to be known in advance, and you can transfer any file in small parts. You still need to make the code on the server (like PHP) in order to accept the file and do what you need.
Use HttpURLConnection to start the connection. Then use my attached class to send data. It will create the correct headers, etc., and you will use it as an OutputStream to write your raw data, then call close, and you're done. You can override it onHandleResult to handle the received error code.
public class FormDataWriter extends FilterOutputStream{ private final HttpURLConnection con; FormDataWriter(HttpURLConnection con, String formName, String fileName, long fileSize) throws IOException{ super(null); this.con = con; con.setDoOutput(true); String boundary = generateBoundary(); con.setRequestProperty(HTTP.CONTENT_TYPE, "multipart/form-data; charset=UTF-8; boundary="+boundary); { StringBuilder sb = new StringBuilder(); writePartHeader(boundary, formName, fileName==null ? null : "filename=\""+fileName+"\"", "application/octet-stream", sb); headerBytes = sb.toString().getBytes("UTF-8"); sb = new StringBuilder(); sb.append("\r\n"); sb.append("--"+boundary+"--\r\n"); footerBytes = sb.toString().getBytes(); } if(fileSize!=-1) { fileSize += headerBytes.length + footerBytes.length; con.setFixedLengthStreamingMode((int)fileSize); }else con.setChunkedStreamingMode(0x4000); out = con.getOutputStream(); } private byte[] headerBytes, footerBytes; private String generateBoundary() { StringBuilder sb = new StringBuilder(); Random rand = new Random(); int count = rand.nextInt(11) + 30; int N = 10+26+26; for(int i=0; i<count; i++) { int r = rand.nextInt(N); sb.append((char)(r<10 ? '0'+r : r<36 ? 'a'+r-10 : 'A'+r-36)); } return sb.toString(); } private void writePartHeader(String boundary, String name, String extraContentDispositions, String contentType, StringBuilder sb) { sb.append("--"+boundary+"\r\n"); sb.append("Content-Disposition: form-data; charset=UTF-8; name=\""+name+"\""); if(extraContentDispositions!=null) sb.append("; ").append(extraContentDispositions); sb.append("\r\n"); if(contentType!=null) sb.append("Content-Type: "+contentType+"\r\n"); sb.append("\r\n"); } @Override public void write(byte[] buffer, int offset, int length) throws IOException{ if(headerBytes!=null) { out.write(headerBytes); headerBytes = null; } out.write(buffer, offset, length); } @Override public void close() throws IOException{ flush(); if(footerBytes!=null) { out.write(footerBytes); footerBytes = null; } super.close(); int code = con.getResponseCode(); onHandleResult(code); } protected void onHandleResult(int code) throws IOException{ if(code!=200 && code!=201) throw new IOException("Upload error code: "+code); } }
Pointer null
source share