Android File Upload Using HTTP PUT

后端 未结 2 1031
囚心锁ツ
囚心锁ツ 2021-01-14 00:05

I have a web service which requires me to send file data to HTTP url with PUT request. I know how to do that but in Android I don\'t know it.

The API docs gives a sa

相关标签:
2条回答
  • 2021-01-14 00:24

    try something similar to

    try {
    URL url = new URL(Host + "images/upload/" + Name + "/");
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setDoOutput(true);
    conn.setRequestMethod("PUT");
        // etc.
    
        } catch (Exception e) { //handle the exception !}
    

    EDIT - another and better option:

    Using the built-in HttpPut is recommended - examples see http://massapi.com/class/org/apache/http/client/methods/HttpPut.java.html

    EDIT 2 - as requested per comment:

    Use setEntity method with for example new FileEntity(new File(Path), "binary/octet-stream"); as param before calling execute to add a file to the PUT request.

    0 讨论(0)
  • 2021-01-14 00:29

    The following code works fine for me:

    URI uri = new URI(url);
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost post = new HttpPost(uri);
    
    File file = new File(filename);         
    
    MultipartEntity entity = new MultipartEntity();
    ContentBody body = new FileBody(file, "image/jpeg");
    entity.addPart("userfile", body);
    
    post.setEntity(entity);
    HttpResponse response = httpclient.execute(post);
    HttpEntity resEntity = response.getEntity();
    
    0 讨论(0)
提交回复
热议问题