Sending files using POST with HttpURLConnection

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

    I tried the solutions above and none worked for me out of the box.

    However http://www.baeldung.com/httpclient-post-http-request. Line 6 POST Multipart Request worked within seconds

    public void whenSendMultipartRequestUsingHttpClient_thenCorrect() 
      throws ClientProtocolException, IOException {
        CloseableHttpClient client = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost("http://www.example.com");
    
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.addTextBody("username", "John");
        builder.addTextBody("password", "pass");
        builder.addBinaryBody("file", new File("test.txt"),
          ContentType.APPLICATION_OCTET_STREAM, "file.ext");
    
        HttpEntity multipart = builder.build();
        httpPost.setEntity(multipart);
    
        CloseableHttpResponse response = client.execute(httpPost);
        client.close();
    }
    

提交回复
热议问题