I am trying to extend a classic ASP site by connecting to some WCF web services using SOAP 1.2 messages. So on the client end, there is no binding I am just using XMLHTTP.
I am getting the dreaded "The message with To '' cannot be processed at the receiver, due to an AddressFilter mismatch at the EndpointDispatcher." error.
My client is using a self-signed SSL cert, and the service end has an SSL cert set up as well.
Most of the solutions to this problem involve ServiceBehavior config on the client to turn off the Address Filter but that's not applicable in this case. Any help?
Code
I created a class in VBScript
Class SOAPRequest
Private objXMLHttp, webServiceURL, contentType
Public servicePath, XmlNS, action, SOAPRequest, SOAPResponse
Private Sub Class_Initialize
set objXMLHttp = Server.CreateObject("MSXML2.XMLHTTP")
webServiceURL = Application("Web Service URL")
contentType = "application/soap+xml;charset=UTF-8"
End Sub
Public Function SendRequest
'Open HTTP connection
objXMLHttp.Open "POST", webServiceURL & "/wcf/" & servicePath, False
'Setting request headers
objXMLHttp.setRequestHeader "Content-Type", contentType
objXMLHttp.setRequestHeader "SOAPAction", webServiceURL & "/wcf/" & servicePath & "?wsdl"
dim SOAPEnvelopeStart, SOAPEnvelopeEnd
SOAPEnvelopeStart = "<?xml version='1.0' encoding='utf-8'?><soap:Envelope xmlns:soap='http://www.w3.org/2003/05/soap-envelope' xmlns:urn='" & XmlNS & "'><soap:Header/><soap:Body>"
SOAPEnvelopeEnd = "</soap:Body></soap:Envelope>"
'Send SOAP request
objXMLHttp.Send SOAPEnvelopeStart & SOAPRequest & SOAPEnvelopeEnd
'Get XML Response
SOAPResponse = objXMLHttp.ResponseText
End Function
Public Function Close
Set objXMLHttp = Nothing
End Function
End Class
and then I call it as such
set objSOAP = New SOAPRequest
'set up the request
with objSOAP
.servicePath = "myservice.svc"
.XmlNS = "urn:MyNamespace"
.action = "Action"
.SOAPRequest = "<urn:GetMyData></urn:GetMyData>"
end with
objSOAP.SendRequest
Related
I am trying to create a Betfair app written in VB.NET using Betfair NG API.
I am trying to request the navigation menu in VB.NET utilizing the following instructions, here, but I get error 400 Bad request. Could someone send me a code for doing so?
Sub GetNavigatorManu(ByVal SessToken As String, ByVal AppKey As String)
Dim request As HttpWebRequest = Nothing
Dim response As HttpWebResponse = Nothing
Dim strResponseStatus As String = ""
Try
request = WebRequest.Create(New Uri("https://api.betfair.com/exchange/betting/rest/v1/en/navigation/menu.json"))
request.Accept = "application/json"
request.Method = "GET"
request.KeepAlive = True
request.ContentType = "application/json"
request.AutomaticDecompression = DecompressionMethods.GZip Or DecompressionMethods.Deflate
request.Headers.Add("Accept-Encoding", "gzip,deflate")
request.Headers.Add("X-Authentication", SessToken)
request.Headers.Add("X-Application", AppKey)
response = request.GetResponse()
Display the status below
strResponseStatus = "Status is " & CType(response, HttpWebResponse).StatusCode
Catch ex As Exception
MsgBox("CreateRequest Error" & vbCrLf & ex.Message)
End Try
MsgBox(strResponseStatus)
End Sub
I am currently trying to use MSXML2.ServerXMLHTTP to send a POST http request.
I need to add a custom header "Auth" so that my requests get authorized but it doesn't seem to work.
Here is the code for my post function:
Function post(path As String, authToken As String, postData As String) As String
Dim xhr As Object
Dim message As String
On Error GoTo error:
Set xhr = CreateObject("MSXML2.ServerXMLHTTP")
xhr.Open "POST", path, False
xhr.setRequestHeader "Content-Type", "application/json"
xhr.setRequestHeader "Auth", authToken
xhr.send postData
If xhr.Status = 200 Then
message = xhr.responseText
Else
message = xhr.Status & ": " & xhr.statusText
End If
Set xhr = Nothing
post = message
error:
Debug.Print "Error " & Err.Number; ":" & Err.Description
End Function
And I end up with "Error -2147012746 Requested Header was not found" (The message is actually translated since I use a different language on my computer).
However I didn't have this problem with the "Microsoft.XMLHTTP" Object.
Am I doing something wrong ?
Thank you for your time.
Try changing the call to SetRequestHeader to use a string literal. I duplicated the problem when authToken does not have a value set.
Change from this
xhr.setRequestHeader "Auth", authToken
To this
xhr.setRequestHeader "Auth", "testdatahere"
I have a computer running Windows Server 2012 that I use to run a lot of my applications. Most of them are processing many asynchronous web requests in parallel (using HttpClient in .NET 4.5).
When I check NETSTAT, I see almost all available (assuming 66,536 is the maximum) ports are in use. The piped output from the basic NETSTAT call is a 4mb text file with 64,583 lines. The majority of these are in TIME_WAIT, lots are not attributed to any particular process but labelled as "System Process".
I understand TIME_WAIT is not necessarily a bad thing and my applications do not seem to be throwing exceptions explicitly stating they are unable to complete a request due to no available ports. However, this concerns me and I'm worried it might be causing time outs.
Is this to be expected? Should I reduce the TcpTimedWaitDelay value in the registry? I believe connections are kept in TIME_WAIT for 4 minutes by default. Also is it possible I'm doing something wrong in my code that leaves connections open like this? I reuse the HttpClient object where possible and always dispose of it when finished. Should I be looking out for connection: close headers in responses?
EDIT: Adding code, as requested. Here's the function that makes the request (part of a custom class wrapper for HttpClient);
Public Async Function WebRequestAsync(Url As String, Optional RequestMethod As RequestMethod = RequestMethod.GET, Optional Content As Object = Nothing, _
Optional ContentType As ContentType = ContentType.Default, Optional Accept As String = DefaultAcceptString, _
Optional AdditionalHeaders As NameValueCollection = Nothing, Optional Referer As String = Nothing, _
Optional NoCache As Boolean = False, Optional CustomCookieHandler As Boolean = False, _
Optional Attempts As Integer = 2, Optional CanBeCancelled As Boolean = True) _
As Tasks.Task(Of HttpResponseMessage)
If Attempts < 1 Then Attempts = 1
Dim Method As HttpMethod = Nothing
Select Case RequestMethod
Case Variables.RequestMethod.DELETE : Method = HttpMethod.Delete
Case Variables.RequestMethod.GET : Method = HttpMethod.Get
Case Variables.RequestMethod.OPTIONS : Method = HttpMethod.Options
Case Variables.RequestMethod.POST : Method = HttpMethod.Post
Case Variables.RequestMethod.PUT : Method = HttpMethod.Put
End Select
'prepare message
Dim Message As New HttpRequestMessage(Method, Url)
Message.Headers.ExpectContinue = False
Message.Headers.TryAddWithoutValidation("Accept", Accept)
If Referer IsNot Nothing Then Message.Headers.Add("Referer", Referer)
If NoCache Then
Message.Headers.Add("Pragma", "no-cache")
Message.Headers.Add("Cache-Control", "no-cache")
End If
If AdditionalHeaders IsNot Nothing Then
For Each Key In AdditionalHeaders.AllKeys
Message.Headers.TryAddWithoutValidation(Key, AdditionalHeaders(Key))
Next
End If
'set content
If Content IsNot Nothing Then
Dim ContentTypeString As String = GetEnumDescription(ContentType)
Dim ContentBytes As Byte() = Nothing
If TypeOf Content Is String Then
ContentBytes = Encoding.UTF8.GetBytes(CType(Content, String))
ElseIf TypeOf Content Is Byte() Then
ContentBytes = CType(Content, Byte())
ElseIf TypeOf Content Is MultiPartPostData Then
Dim MultiPartPostData As MultiPartPostData = CType(Content, MultiPartPostData)
ContentBytes = MultiPartPostData.Bytes
ContentTypeString += "; boundary=" & MultiPartPostData.Boundary
End If
Dim ByteArrayContent As New ByteArrayContent(ContentBytes)
ByteArrayContent.Headers.Add("Content-Type", ContentTypeString)
Message.Content = ByteArrayContent
End If
'get response
Output(RequestMethod.ToString & " " & Url, OutputType.Debug)
'Set cancellation token
Dim CToken As New CancellationToken
If CancellationToken IsNot Nothing AndAlso CancellationToken.HasValue AndAlso CanBeCancelled Then CToken = CancellationToken.Value
Dim Response As HttpResponseMessage = Nothing
For Attempt = 1 To Attempts
Try
Response = Await Client.SendAsync(Message, HttpCompletionOption.ResponseHeadersRead, CToken).ConfigureAwait(False)
Catch ex As Tasks.TaskCanceledException
If DebugMode Then Output(Method.ToString & " " & Url & " Timed out", OutputType.Error)
Catch ex As HttpRequestException
If ex.InnerException IsNot Nothing Then
If DebugMode Then Output(Method.ToString & " " & Url & " " & ex.InnerException.Message, OutputType.Error)
If ex.InnerException.Message = "Timed out" Then Continue For
Else
If DebugMode Then Output(Method.ToString & " " & Url & " " & ex.Message, OutputType.Error)
End If
Catch ex As Exception
If DebugMode Then Output(Method.ToString & " " & Url & " " & ex.Message, OutputType.Error)
End Try
Exit For
Next
If Response IsNot Nothing Then
Output(Method.ToString & " " & Url & " " & Response.StatusCode & " " & Response.StatusCode.ToString, OutputType.Debug)
If CustomCookieHandler AndAlso Cookies IsNot Nothing Then
Dim Values As IEnumerable(Of String) = Nothing
If Response.Headers.TryGetValues("Set-Cookie", Values) Then ManuallyExtractCookies(Values, New Uri(Url).GetLeftPart(UriPartial.Authority))
End If
End If
Return Response
End Function
And an example of making a request;
Using HttpClient As New HttpClientWrapper(User, Task)
Dim Response As String = Await HttpClient.WebRequestStringAsync("http://www.google.com")
If Response Is Nothing Then Return Nothing
End Using
In HTTP 1.1, all connections are considered persistent unless declared
otherwise.
So if you don't close the connection the server will keep waiting for a new request (at least until certain timeout).
The solution would be to add a Connection: close header or explicitly close the connection after receiving the response: Response.Dispose().
I've got a problem with my VB.Net-application. When i'm trying to send a request to http://ask.fm without proxy, i got the following response in fiddler: HTTP/1.1 502 Fiddler - DNS Lookup Failed
What does this mean? And why is there no error when using a proxy server for the request?
I send the request with the following code:
Public Function GetRequest(ByVal url As String, ByVal referer As String, ByVal cookie As CookieContainer, Optional proxy As String = "") As String
Dim request As HttpWebRequest
Dim response As HttpWebResponse
Try
Dim cookies As String = ""
request = CType(HttpWebRequest.Create(url), HttpWebRequest)
request.CookieContainer = cookie
request.ServicePoint.Expect100Continue = False
request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; rv:8.0) Gecko/20100101 Firefox/8.0"
If referer <> "" Then
request.Referer = referer
End If
request.Timeout = 10000
If proxy <> "" Then
request.Proxy = New WebProxy(proxy)
End If
response = CType(request.GetResponse(), HttpWebResponse)
cookies = response.GetResponseHeader("Set-Cookie")
If url.Contains("ask.fm/") Then
If New Regex("l=.*?; domain=ask.fm; path=/;").Match(cookies).Value = "" Then
Return "ERROR"
End If
End If
Dim source As String = New StreamReader(response.GetResponseStream()).ReadToEnd()
If source.Contains("No robots allowed!") Then
source = "ERROR"
End If
If source = "" Then
source = "ERROR"
End If
Return source
Catch ex As Exception
Return "ERROR"
End Try
End Function
Are you using Fiddler to inspect the traffic? If so, make sure Fiddler can redirect your traffic correctly.
Go to Help > About Fiddler and make sure your Gateway is correct (either set to the proxy you use for accessing internet or equal to No Gateway if you can access directly).
How can one pass http get or post methods to a windows application? I require a webserver to send a get method to my windows form application that will query a database then reply back to a webserver
I'm developing a windows based search engine that searches a MySQL database. It receives a keyword from an SMS gateway software as a HTTP get request and should reply to the gateway software using the same HTTP request.This is my code. It is correctly searching the database but I don't know how to receive the get methods on the application however it's sending the messages to SMS gateway.
Private Sub bSend_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bSend.Click
Dim request As HttpWebRequest
Dim response As HttpWebResponse = Nothing
Dim url As String
Dim username As String = "admin"
Dim password As String = "abc123"
Dim host As String = "http://127.0.0.1:9501"
Dim originator As String = "0724116972"
Try
url = host + "/api?action=sendmessage&" _
& "username=" & HttpUtility.UrlEncode(username) _
& "&password=" + HttpUtility.UrlEncode(password) _
& "&recipient=" + HttpUtility.UrlEncode(tbReceiver.Text) _
& "&messagetype=SMS:TEXT" _
& "&messagedata=" + HttpUtility.UrlEncode(tbMessage.Text) _
& "&originator=" + HttpUtility.UrlEncode(originator) _
& "&serviceprovider=" _
& "&responseformat=html"
request = DirectCast(WebRequest.Create(url), HttpWebRequest)
response = DirectCast(request.GetResponse(), HttpWebResponse)
MessageBox.Show("Response: " & response.StatusDescription)
Catch ex As Exception
MessageBox.Show("Error. Server Not running")
Me.Close()
End Try
End Sub
End Class
sounds like you want to host a webserver in your winforms application...you can use HttpListener - see http://msdn.microsoft.com/en-us/library/system.net.httplistener.aspx
IF your application is not running as Administrator you will need to register the URL you are listerning to with netsh though