Webclient or HTTPWebrequest post with file and form elements

N

Natalia

Hello,

I need to provide the ability to post file and some form elements via
our website (asp.net) to the third party website (asp page). On
http://aspalliance.com/236#Page4 - I found great advices but still
having troubles... it might some obvious error that I am making but I
just dont see it.


==================FIRST - Webclient=================================
RESULT: Exception : ProtocolError (server 500 error)
================================================================
Dim url as String = "http://www.site2post.com"
Dim q As New System.Collections.Specialized.NameValueCollection
q.Add("id", "123456789")
q.Add("merchant_pin", "987654321")


Dim wc As New System.Net.WebClient
wc.Headers.Add("Content-Type",
"application/x-www-form-urlencoded")
wc.QueryString = q


Dim responseArray As Byte() = wc.UploadFile(url, "POST",
"C:\folder\file.txt")
If responseArray.Length > 0 Then
resultString &=
System.Text.Encoding.ASCII.GetString(responseArray).ToString
Else
resultString &= "No response"
End If


=============SECOND- HTTPWebREQUEST ===========================
RESULT: can pass variables but can not pass the file.
================================================================


Dim url as String =
"http://www.site2post.com?id=123456789&merchant_pin=987654321"
Dim strFileToUse As String = "C:\folder\file.txt"
Dim st As New FileStream(strFileToUse, FileMode.Open)
Dim Tem() As Byte
ReDim Tem(st.Length)
st.Read(Tem, 0, st.Length)
st.Close()


Dim req As System.Net.HttpWebRequest
req = System.Net.WebRequest.Create(url)
'--set the standard header information
req.ProtocolVersion = HttpVersion.Version11


req.Method = "POST"
req.Accept = "*/*"
req.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT
5.1; .NET CLR 1.0.3705)"
req.ContentType = "application/x-www-form-urlencoded"
'req.AllowAutoRedirect = False
req.ContentLength = Tem.Length
'--set additional header information
req.Headers.Add("id", "123456789")
req.Headers.Add("merchant_pin", "987654321")


' Perform the request
Dim requestStream As Stream = req.GetRequestStream()
requestStream.Write(Tem, 0, Tem.Length)
requestStream.Close()


'read in the page
Dim res As System.Net.HttpWebResponse
res = req.GetResponse()
If req.HaveResponse Then
Dim sr As System.IO.StreamReader
sr = New
System.IO.StreamReader(res.GetResponseStream())
resultString = sr.ReadToEnd
sr.Close()
End If
res.Close()


Please help.
Thanks in advance.
Natalia
 
B

bruce barker

you need to send a multi-part form. the file should be a mime attachment.

Content-type: multipart/mixed; boundary=23xx1211
CRLF
--23xx1211
Content-type: application/x-www-form-urlencoded
CRLF
a=123&b=345
--23xx1211
Content-type: text/xml
CRLF
<a/a>
--23xx1211--
 
N

Natalia

I have got :
System.Net.WebException: The Content-Type header cannot be set to a
multipart type for this request.
 
B

bruce barker

i don't believe WebClient supports multipart, you have to use the lower
level HttpWebRequest.

-- bruce (sqlwork.com)
 
N

Natalia

Ok, I rethink the logic to use HTTPWebRequest as recommended...

Now I am passing parameters in the postURL = "http://site.com?par1=xx&par2=yy".

I do receive the response from the other server back with values, but not file received. What is the problem!?

===============================================================
Private Function DoWebRequest(ByVal postURL As String, ByVal fileURL As String) As String
Dim boundary As String = Guid.NewGuid().ToString().Replace("-", "")

'DECLARE A FILE===
Dim formdata_Bytes As Byte() = System.Text.Encoding.ASCII.GetBytes("--" & boundary & vbCrLf & "Content-Disposition: form-data; name=\""batch_file\""" & vbCrLf & "content-type: text/plain; charset=windows-1250" & vbCrLf & "content-transfer-encoding:quoted-printable" & vbCrLf & vbCrLf & "VALUE" & vbCrLf & "--" & boundary & "--" & vbCrLf)

'GET FILE===
Dim sF As New FileStream(fileURL, FileMode.Open, FileAccess.Read)
Dim Tem() As Byte
ReDim Tem(sF.Length)
sF.Read(Tem, 0, sF.Length)
sF.Close()

'JOIN FILE DECLARATION AND FILE CONTENTS ===
Dim ByteArrayToSend() As Byte
ReDim ByteArrayToSend(formdata_Bytes.Length + Tem.Length) 'make it big enough
formdata_Bytes.CopyTo(ByteArrayToSend, 0) 'copy Body starting @ 0
Tem.CopyTo(ByteArrayToSend, formdata_Bytes.Length - 1) 'copy File starting @ Body.Length(-1)

'MAKE WEBREQUEST ===
Dim req As HttpWebRequest = DirectCast(WebRequest.Create(postURL), HttpWebRequest)
req.Method = "post"
req.ContentType = "multipart/form-data; boundary=" & boundary
req.ContentLength = ByteArrayToSend.Length

Dim sD As Stream
Try
sD = req.GetRequestStream()
sD.Write(ByteArrayToSend, 0, ByteArrayToSend.Length) 'file content ===
sD.Flush()
Dim res As HttpWebResponse = req.GetResponse()
Dim sr As StreamReader = New StreamReader(res.GetResponseStream())
DoWebRequest = sr.ReadToEnd
sr.Close()
res.Close()

Catch ex As WebException
If ex.Status = WebExceptionStatus.Timeout Then
DoWebRequest = "Timeout error"
Else
DoWebRequest = ex.Message & "<br>"
End If
Finally
sD.Close()
End Try

End Function
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,820
Messages
2,569,721
Members
45,509
Latest member
Danish324

Latest Threads

Top