Android Tutorial Android Http Multipart requests

Status
Not open for further replies.
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:
B4X:
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:
B4X:
    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.
 

Attachments

  • MultipartPost.bas
    2 KB · Views: 2,047
Last edited:

optimist

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

i suggest the following change:

old:
B4X:
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:
B4X:
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.
 

Swissmade

Well-Known Member
Licensed User
Longtime User
thank you for this code.
but in my opinion there is a problem with the content-type.

i suggest the following change:

old:
B4X:
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:
B4X:
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.
Many thanks for this correction.
Has help me out.

Cheers,
Swissmade
 

Neojoy

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

Thanks
 

ashrafidkaidek

Member
Licensed User
Longtime 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
 

ashrafidkaidek

Member
Licensed User
Longtime User
I have used the above code to get the error details:

B4X:
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:

B4X:
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:

ednt

Member
Licensed User
Longtime 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
 

sangee

Member
Licensed User
Longtime 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 ...
 

RjCl

Member
Licensed User
Longtime User
Erel,

Is Response.GetString deprecated now and won't work on Android 4+ ?
 
Status
Not open for further replies.
Top