Sending files using POST with HttpURLConnection

前端 未结 10 1390
攒了一身酷
攒了一身酷 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:22

    I haven't tested this, but you might try using PipedInputStream and PipedOutputStream. It might look something like:

    final Bitmap bmp = … // your bitmap
    
    // Set up Piped streams
    final PipedOutputStream pos = new PipedOutputStream(new ByteArrayOutputStream());
    final PipedInputStream pis = new PipedInputStream(pos);
    
    // Send bitmap data to the PipedOutputStream in a separate thread
    new Thread() {
        public void run() {
            bmp.compress(Bitmap.CompressFormat.PNG, 100, pos);
        }
    }.start();
    
    // Send POST request
    try {
        // Construct InputStreamEntity that feeds off of the PipedInputStream
        InputStreamEntity reqEntity = new InputStreamEntity(pis, -1);
    
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(url);
        reqEntity.setContentType("binary/octet-stream");
        reqEntity.setChunked(true);
        httppost.setEntity(reqEntity);
        HttpResponse response = httpclient.execute(httppost);
    } catch (Exception e) {
        e.printStackTrace()
    }
    

提交回复
热议问题