Sending files using POST with HttpURLConnection

前端 未结 10 1381
攒了一身酷
攒了一身酷 2020-11-22 15:45

Since the Android developers recommend to use the HttpURLConnection class, I was wondering if anyone can provide me with a good example on how to send a bitmap

10条回答
  •  迷失自我
    2020-11-22 16:40

    I have no idea why the HttpURLConnection class does not provide any means to send files without having to compose the file wrapper manually. Here's what I ended up doing, but if someone knows a better solution, please let me know.

    Input data:

    Bitmap bitmap = myView.getBitmap();
    

    Static stuff:

    String attachmentName = "bitmap";
    String attachmentFileName = "bitmap.bmp";
    String crlf = "\r\n";
    String twoHyphens = "--";
    String boundary =  "*****";
    

    Setup the request:

    HttpURLConnection httpUrlConnection = null;
    URL url = new URL("http://example.com/server.cgi");
    httpUrlConnection = (HttpURLConnection) url.openConnection();
    httpUrlConnection.setUseCaches(false);
    httpUrlConnection.setDoOutput(true);
    
    httpUrlConnection.setRequestMethod("POST");
    httpUrlConnection.setRequestProperty("Connection", "Keep-Alive");
    httpUrlConnection.setRequestProperty("Cache-Control", "no-cache");
    httpUrlConnection.setRequestProperty(
        "Content-Type", "multipart/form-data;boundary=" + this.boundary);
    

    Start content wrapper:

    DataOutputStream request = new DataOutputStream(
        httpUrlConnection.getOutputStream());
    
    request.writeBytes(this.twoHyphens + this.boundary + this.crlf);
    request.writeBytes("Content-Disposition: form-data; name=\"" +
        this.attachmentName + "\";filename=\"" + 
        this.attachmentFileName + "\"" + this.crlf);
    request.writeBytes(this.crlf);
    

    Convert Bitmap to ByteBuffer:

    //I want to send only 8 bit black & white bitmaps
    byte[] pixels = new byte[bitmap.getWidth() * bitmap.getHeight()];
    for (int i = 0; i < bitmap.getWidth(); ++i) {
        for (int j = 0; j < bitmap.getHeight(); ++j) {
            //we're interested only in the MSB of the first byte, 
            //since the other 3 bytes are identical for B&W images
            pixels[i + j] = (byte) ((bitmap.getPixel(i, j) & 0x80) >> 7);
        }
    }
    
    request.write(pixels);
    

    End content wrapper:

    request.writeBytes(this.crlf);
    request.writeBytes(this.twoHyphens + this.boundary + 
        this.twoHyphens + this.crlf);
    

    Flush output buffer:

    request.flush();
    request.close();
    

    Get response:

    InputStream responseStream = new 
        BufferedInputStream(httpUrlConnection.getInputStream());
    
    BufferedReader responseStreamReader = 
        new BufferedReader(new InputStreamReader(responseStream));
    
    String line = "";
    StringBuilder stringBuilder = new StringBuilder();
    
    while ((line = responseStreamReader.readLine()) != null) {
        stringBuilder.append(line).append("\n");
    }
    responseStreamReader.close();
    
    String response = stringBuilder.toString();
    

    Close response stream:

    responseStream.close();
    

    Close the connection:

    httpUrlConnection.disconnect();
    

    PS: Of course I had to wrap the request in private class AsyncUploadBitmaps extends AsyncTask, in order to make the Android platform happy, because it doesn't like to have network requests on the main thread.

提交回复
热议问题