HttpWebRequest received error 406 and Fiddler seems to have confused things - asp.net

I am using the following code....
Dim myHttpWebRequest As HttpWebRequest = CType(WebRequest.Create(PostingUrl), HttpWebRequest)
myHttpWebRequest.Method = "POST"
myHttpWebRequest.Headers.Add("Authorization", "Bearer " & RSettings.access_token)
myHttpWebRequest.Headers.Add("Accept-Version", "2")
myHttpWebRequest.ContentType = "application/json; charset=UTF-8"
myHttpWebRequest.Accept = "application/json"
' myHttpWebRequest.Proxy = Nothing ' ** SEE NOTES ON THIS LINE **
Dim Byt As Byte() = Encoding.UTF8.GetBytes(DataString)
Using stream = myHttpWebRequest.GetRequestStream()
stream.Write(Byt, 0, Byt.Length)
End Using
Using myHttpWebResponse As HttpWebResponse = CType(myHttpWebRequest.GetResponse(), HttpWebResponse)
Using srRead As New StreamReader(myHttpWebResponse.GetResponseStream())
ListingResponse = srRead.ReadToEnd()
End Using
End Using
Where:
PostingUrl is "https://reverb.com/api/listings"
RSettings.access_token is (obviously) my access token for this API
DataString is a JSON string posting the data to the Reverb API
If I run my code from Visual Studio (localhost) it returns
The remote server returned an error: (406) Not Acceptable.
Trying to figure out why, I opened Fiddler hoping I could inspect content types and figure out the problem, but the response error changed to:
The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel. ---> System.Security.Authentication.AuthenticationException: The remote certificate is invalid according to the validation procedure.
(I'm guessing from this error that I also have an issue with my Auth key, but that's a separate subject I think.)
After a bit of Googling and S/O pages I found two suggestions:
Tools > Fiddler Options > HTTPS and uncheck "Capture HTTPS CONNECTs"
Add the commented out line: myHttpWebRequest.Proxy = Nothing
If I make any of those changes, I get back to my Error 406 that I get without Fiddler running.
However, if I add myHttpWebRequest.Proxy = Nothing line added, I can no longer see the Tunnel to http://reverb.com:443 Log entry in Fiddler, there's no record of a request to Reverb.com so I can't inspect anything.
I'm now very confused about what I'm doing, and I guess haven't actually made any progress at all!
I still have error 406 and don't seem to be able to inspect the headers/content type issues with Fiddler as I had hoped (please explain how if I am wrong!)
Even if I do correct the 406, I think I have an authentication error.
By the way... all this is an attempt to recreate the cURL example on the Rever docs page here:
https://dev.reverb.com/docs/create-a-listing
I have also been discussing this issue here:
https://dev.reverb.com/v1.0/discuss/57bb2ca0aa8f760e004588cf

Argh... well, my confusing over Fiddler still stands but the 406 error was caused by this:
myHttpWebRequest.Headers.Add("Accept-Version", "2")
Should have been
myHttpWebRequest.Headers.Add("Accept-Version", "2.0")
How simple!!

Related

Windows server 2003 - The underlying connection was closed: An unexpected error occurred on a send. Seeing a "Handshake Failure (40)" in wireshark

Update: the code works on my desktop so it appears to be an issue with my server
I am trying to post some XML using vb/asp.net 4.0 via:
Dim request As HttpWebRequest = HttpWebRequest.Create(thePostingURL)
My code works for many clients, however there is one that I cannot seem to connect to.
I have attempted to research this and things I have tried based on posts I found are:
request.KeepAlive = False
request.KeepAlive = True
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls Or SecurityProtocolType.Ssl3
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3
Not all at the same time of course. I have tried running Wireshark while posting the XML and it appears to be failing on a "Handshake Failure (40)."
The client's url is https.
Not sure if this is a clue or not, but I cannot access the URL via IE8 while I can using Chrome. This is on a windows 2003 server.
Any ideas or suggestions of things to try?

Request.Form between HTTP and HTTPS pages in ASP.NET

I have a strange situation and google isn't helping me out. I have an admin site which is in simple HTTP who posts data to a different site running under HTTPS. The HTTP admin site (which I don't have direct access to) is sending the info via basic POST, and I'm trying to capture the Request.Form values in the HTTPS site. It works perfectly well in dev, due to the fact that the receiving site isn't running under SSL, but in prod, I have the Request.Form as empty. Someone could enlighten me? The basic HTTPS request code is below:
Dim nvm As NameValueCollection = Request.Form
Dim _idInscricao As String
Dim _Origem As String
litMensagem.Text = "Wait..."
If nvm.Keys.Count = 0 Then
litMensagem.Text = "Error recovering data. No keys found."
Exit Sub
End If
For Each _Key As String In nvm.Keys
If _Key.ToLower.EndsWith("idinscricao") Then
_idInscricao = nvm(_Key)
End If
If _Key.ToLower.EndsWith("origem") Then
_Origem = nvm(_Key)
End If
Next
If _idInscricao Is Nothing OrElse String.IsNullOrEmpty(_idInscricao) _
OrElse _Origem Is Nothing OrElse String.IsNullOrEmpty(_Origem) Then
litMensagem.Text = "Error recovering data."
Exit Sub
End If
I found this question because I was having the same problem, and I need to thank dana for the fiddler recommendation.
Using Fiddler, I found out what was going on. My page was on HTTPS, and the form that I was posting posted to HTTP. I couldn't figure out why my form structure on the posted page was empty.
Turns out the server couldn't find the http version of the file and did an automatic redirect to the https version, doing a GET with my form variables. They aren't available in the form scope with a GET. (FWIW, I'm using CFML.)
Once I changed the form action to post to HTTPS, everything worked like a charm.
-jason

http post with blackberry

I am trying to set up an http post in my Blackberry app. I have successfully implemented this in my corresponding Android app, so I know the server it working find. I have tried several different things, and I'm not really getting errors, its just the info on the server is not getting updated. I have looked at this post:
Http POST in BlackBerry, and several others. I found them helpful, but they didn't ultimately solve my problem. Again, I don't get errors, but the server doesn't get updated. Here is the code I am currently using:
String url = "http://xxxx.com/ratings/add?;deviceside=true";
String postStr1 = "business_id=790";
String postStr2 = "&rating=4";
HttpConnection httpConnection = (HttpConnection) Connector.open(url);
httpConnection.setRequestMethod(HttpConnection.POST);
httpConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
URLEncodedPostData encPostData = new URLEncodedPostData("UTF-8", false);
encPostData.append("business_id", String.valueOf(790));
encPostData.append("rating", String.valueOf(4));
byte[] postData = encPostData.toString().getBytes("UTF-8");
httpConnection.setRequestProperty("Content-Length", String.valueOf(postData.length));
OutputStream os = httpConnection.openOutputStream();
os.write(postData);
os.flush();
Anyone have any ideas on what could be wrong?
A few things were going on. First, my simulator was not connecting to the internet properly. Once that got straightened out, I removed the
deviceside=true
from my url, and it now works great. Thanks all!

Android C2DM getting (401) Unauthorized

I have an Android application with an ASP.NET backend. I have the registration_id for the phone as well as an auth token from google for the application server that is performing a push.
When I make the http post request to C2DM so that the phone gets a message I keep getting the 401 Unauthorized. Here is how I'm making the request in .NET:
WebRequest myRequest = WebRequest.Create("https://android.apis.google.com/c2dm/send");
myRequest.ContentType = "application/x-www-form-urlencoded";
myRequest.Method = "POST";
myRequest.Headers.Add("Authorization", "GoogleLogin auth=" + authId);
// buiold the post string
StringBuilder myPost = new StringBuilder();
myPost.AppendFormat("registration_id={0}", regId);
myPost.AppendFormat("&data.payload={0}", msg);
myPost.AppendFormat("&collapse_key={0}", colKey);
// write the post-string as a byte array
byte[] myData = ASCIIEncoding.ASCII.GetBytes(myPost.ToString());
myRequest.ContentLength = myData.Length;
Stream myStream = myRequest.GetRequestStream();
myStream.Write(myData, 0, myData.Length);
myStream.Close();
// Do the actual request and read the response stream
WebResponse myResponse = myRequest.GetResponse();
Stream myResponseStream = myResponse.GetResponseStream();
StreamReader myResponseReader = new StreamReader(myResponseStream);
string strResponse = myResponseReader.ReadToEnd();
myResponseReader.Close();
myResponseStream.Close();
Any help would be much appreciated.
Advice corner: Have some confidence in your code every once and a while! And, even Google messes up sometimes.
After spending about nine hours reading every blog post and article about Google OAuth and C2DM and trying different things in my code, I emailed Google. I'm excited to say that not only did I receive a response very quickly, but also that my account was messed up. Something went wrong while I was registering on their site and although it appeared that everything was working from the registration success email I received, it wasn't. I re-registered and everything works!
I have encountered a similar problem: error 401 "Unauthorized" while trying a google c2dm (cloud to device messaging) code sample. It looks like the example used to work as is, but now Google has changed its conditions. Before running code examples, you have to sign-up:
http://code.google.com/android/c2dm/signup.html
I signed up, and the stuff began to work in minutes.
I've got the same problem, i.e. suddenly my C2DM_ACCOUNT_EMAIL stopped working.
To solve the problem, just fill the registration again with same info and the same C2DM_ACCOUNT_EMAIL.
HTH

MSXML2.XMLHTTP Request to validate entered URL in ASP Classic

Thanks in advance for any help received.
I want to allow our client to enter a URL into a text field which then checks whether the URL exists and works.
There are 3 possible outcomes I want to check for:
A status of 200 - OK,
A status of 500 - Server Error,
Or a status of 404 - page not found.
When executing the following code in ASP classic I get a status code of 12007 when I should be getting 404. Is this because it can't find a webserver to return a code of 404?
Function CheckURL(vURL)
ON ERROR RESUME NEXT
Set oXML=Server.CreateObject("MSXML2.XMLHTTP") : oXML.Open "POST",vURL,false : oXML.Send()
CheckURL = oXML.status
Set oXML = nothing
End Function
Or is something amiss here. What status codes am I likely to see other than the standard mentioned above.
The 12007 is a Windows HTTP error which means name hasn't been resolved. You can't get a 200, 404, 500 or any such thing if the host name can't be resolved to an IP address or a connection can't be established to that IP address. In these cases you will get error codes in the 12000s range which aren't HTTP status codes but are windows exception numbers.
See this list for a list of these exception numbers.
BTW, XMLHTTP is not a safe item object to use in ASP. Also why are you using a POST? This is the code I would use:-
Function CheckURL(vURL)
On Error Resume Next
Set xhr = CreateObject("MSXML2.ServerXMLHTTP.3.0")
xhr.Open "HEAD", vURL, false
xhr.Send
CheckURL = xhr.status
End Function
Using HEAD allows you test the URL without actually downloading a potentially large entity body.

Resources