Android Tutorial Android Http Multipart requests

Discussion in 'Tutorials & Examples' started by Erel, Mar 26, 2011.

Thread Status:
Not open for further replies.
  1. Erel

    Erel Administrator Staff Member Licensed User

    For new projects it is recommended to use OkHttpUtils2: https://www.b4x.com/android/forum/threads/54723/#content

    Multipart POST requests are usually used by Html Form components to upload files and pairs of name/values to the server.
    The attached code module makes it easy to create such requests.

    The following code demonstrates the usage of this code module:
    Code:
    Sub Process_Globals
        
    Dim hc As HttpClient
    End Sub

    Sub Activity_Create(FirstTime As Boolean)
        
    If FirstTime Then
            hc.Initialize(
    "hc")
        
    End If
        
    'Add files
        Dim files As List
        files.Initialize
        
    Dim FD As FileData
        fd.Initialize
        fd.Dir = 
    File.DirRootExternal
        fd.FileName = 
    "temp.apk"
        fd.KeyName = 
    "upfile2"
        fd.ContentType = 
    "application/octet-stream"
        files.Add(fd)
        
    'Add second file
        Dim fd As FileData
        fd.Initialize
        fd.Dir = 
    File.DirAssets
        fd.FileName = 
    "1.png"
        fd.KeyName = 
    "upfile"
        fd.ContentType = 
    "application/octet-stream"
        files.Add(fd)
        
    'Add name / values pairs (parameters)
        Dim NV As Map
        NV.Initialize
        NV.Put(
    "note1""abc")
        NV.Put(
    "note2""def")
        
    Dim req As HttpRequest
        req = MultipartPost.CreatePostRequest(
    "http://www.example.com/1.php", NV, files)
        hc.Execute(req, 
    1)
    End Sub
    Sub hc_ResponseError (Response As HttpResponse, Reason As String, StatusCode As Int, TaskId As Int)
        
    Log("error: " & Response & " " & StatusCode)
        
    If response <> Null Then
            
    Log(Response.GetString("UTF8"))
            Response.Release
        
    End If
    End Sub
    Sub hc_ResponseSuccess (Response As HttpResponse, TaskId As Int)
        
    Msgbox(Response.GetString("UTF8"), "")
        Response.Release
    End Sub
    The method MultipartPost.CreatePostRequest does most of the job.
    It accepts three parameters. The first is the URL (of the target, not the html page).
    The second is a Map that contains the names and values pairs that will be sent to the server.
    You can pass Null if it is not needed.
    The third parameter is a List that holds FileData items.
    Each FileData item represents a file that will be uploaded to the server.
    Again, you can pass Null if it is not needed.
    For example:
    Code:
    Dim fd As FileData
        fd.Initialize
        fd.Dir = 
    File.DirAssets
        fd.FileName = 
    "1.png"
        fd.KeyName = 
    "upfile"
        fd.ContentType = 
    "application/octet-stream"
    The above code will upload a file named 1.png from the assets folder (Files tab). The file will be mapped to "upfile" key.
     

    Attached Files:

    Last edited: Jan 7, 2016
    icefairy333 and ottomano like this.
  2. bluedude

    bluedude Well-Known Member Licensed User

    Awesome, thanks!
     
  3. optimist

    optimist Member Licensed User

    thank you for this code.
    but in my opinion there is a problem with the content-type.

    i suggest the following change:

    old:
    Code:
    b = ("--" & boundary & EOL & "Content-Disposition: form-data; name=" _ 
                & 
    QUOTE & FD.KeyName & QUOTE & "; filename=" & QUOTE & FD.FileName & QUOTE _
                & 
    ";" & "Content-Type: " & EOL & FD.ContentType & EOL & EOL).GetBytes("UTF8")
    new:
    Code:
    b = ("--" & boundary & EOL & "Content-Disposition: form-data; name=" _ 
                & 
    QUOTE & FD.KeyName & QUOTE & "; filename=" & QUOTE & FD.FileName & QUOTE _
                & EOL & 
    "Content-Type: " & FD.ContentType & EOL & EOL).GetBytes("UTF8")
    Hope this helps :)


    BTW: why is this not part of the official HTTPUtil module? I merged it for me and it works fine. If anybody wants to get the pimped HTTPUtil just drop a line.
     
    icefairy333 and NeverGiveUp2 like this.
  4. Erel

    Erel Administrator Staff Member Licensed User

    Only because it was written before HttpUtils was available.
     
  5. swissmade

    swissmade Active Member Licensed User

    Many thanks for this correction.
    Has help me out.

    Cheers,
    Swissmade
     
  6. Neojoy

    Neojoy Member Licensed User

    Hi Erel, what´s the library to define my variable as "FileData", I can´t find in my list.

    Thanks
     
  7. Erel

    Erel Administrator Staff Member Licensed User

    It is a Type defined in the module attached to the first post.
     
  8. Neojoy

    Neojoy Member Licensed User

    Thank' s Erel, next time I pay more attention:sign0013:
     
  9. ashrafidkaidek

    ashrafidkaidek Member Licensed User

    I have used the above process to upload a txt file to the user SkyDrive account and it worked perfectly fine since over a month ago.

    Without changing anything in my app (no app updates or code change) I start receiving the error below, since about a week ago, when trying to upload a file:

    "Anywheresoftware.b4a.http.Http.ClientWrapper$HttpResponceWrapper@43de13d0415"

    Any idea what is the reason behind this error?

    Thank you all
     
  10. Erel

    Erel Administrator Staff Member Licensed User

    Can you post the full error message from the logs?
     
  11. ashrafidkaidek

    ashrafidkaidek Member Licensed User

    I have used the above code to get the error details:

    Code:
    Sub hc_ResponseError (Response As HttpResponse, Reason As String, StatusCode As Int, TaskId As Int)
        
    Log("error: " & Response & " " & StatusCode)
        
    If response <> Null Then
            
    Log(Response.GetString("UTF8"))
            Response.Release
        
    End If
    End Sub

    When my app tries to upload a text file to user SkyDrive account the "Sub hc_ResponseError" will be called but nothing will be shown in the log! Therefore i have Changed the code above to:

    Code:
    Sub hc_ResponseError (Response As HttpResponse, Reason As String, StatusCode As Int, TaskId As Int)
    Msgbox("error: " & Response & " " & StatusCode, " ")
        
    If response <> Null Then
            
    Log(Response.GetString("UTF8"))
            Response.Release
        
    End If
    End Sub
    And received the message in the attached image:

    Basic4Android Error.png



    I had some miner communication issues with SkyDrive for one of my Windows Phones apps, I have noticed this problem just a week ago after Microsoft updated there Live SDK to V5.4, therefore I have updated the libraries in my app to the latest version and all communication problem were resolved.

    Currently I’m using HTTP v1.26 in my Android app, it seems to me that this library is not fully compatible with latest Microsoft Live SDK . . .

    Any thoughts?

    Thank you all
     
    Last edited: Aug 1, 2013
  12. ednt

    ednt Member Licensed User

    I work on a Project which need MultiPart Post.

    i have try your example, but i did´t find a solution for FileData.
    Where i can find the missing Library ?
    Can you send this example as a complete working filke (zip)

    Thank you all
     
  13. Erel

    Erel Administrator Staff Member Licensed User

    FileData is a Type declared in the code module attached to the first post.
     
  14. sangee

    sangee Member Licensed User

    Hello ... can some one help with the php file which receives the files from these uploads. I am desperately trying with PHP for multipart uploads..

    Thanks ...
     
  15. Erel

    Erel Administrator Staff Member Licensed User

  16. sangee

    sangee Member Licensed User

  17. NeverGiveUp2

    NeverGiveUp2 Member Licensed User

    To Optimist: Thanks for your correction! It helps me very well.
     
  18. LudwigRS

    LudwigRS Member Licensed User

    Thank you very much! This helped me a lot.
     
  19. RjCl

    RjCl Member Licensed User

    Erel,

    Is Response.GetString deprecated now and won't work on Android 4+ ?
     
  20. Erel

    Erel Administrator Staff Member Licensed User

    Yes. You should not use Response.GetString.
     
Thread Status:
Not open for further replies.
Loading...
  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice