Trying to upload an image to HTTP virtual directory and I keep getting this exception:
A first chance exception of type 'System.Net.WebException' occurred in System.dll
at System.Net.HttpWebRequest.GetResponse()
Dim mFileStream As New FileStream("/Image Location/", FileMode.Open)
Dim mRequest As WebRequest = WebRequest.Create("/URL/")
mRequest.Headers.Set("filename", "new name")
mRequest.Proxy = New WebProxy("/URL/", True)
mRequest.Method = "POST"
mRequest.ContentLength = mFileStream.Length
Dim mCredentials As New NetworkCredential
mCredentials.Password = "/pass/"
mCredentials.UserName = "/Login Name/"
mRequest.Credentials = mCredentials
Dim mData(mFileStream.Length - 1) As Byte
mFileStream.Read(mData, 0, mFileStream.Length)
mFileStream.Close()
Using dataStream As Stream = mRequest.GetRequestStream()
dataStream.Write(mData, 0, mData.Length)
dataStream.Close()
End Using
Dim mResponse As HttpWebResponse = CType(mRequest.GetResponse(), HttpWebResponse)
mResponse.Close()
Upon further investigation, I have found the reason for the WebException is:
ProtocolError The remote server returned an error: (405) Method Not Allowed.
The answer was quite simple despite everything i tried
you have to specify the file name in the url
Dim mRequest As WebRequest = WebRequest.Create("/URL/")
to
Dim mRequest As WebRequest = WebRequest.Create("/URL/" & FileName & FileExtention)
ex:
Dim mRequest As WebRequest = WebRequest.Create("http://1.1.1.1/niveimage.png")
Related
I am getting TWO exceptions. The first one in the regular code and the second into the exception handling block.
I have this function (below) that supposed to change user settings in a Web API using PUT method. Everything runs fine until the point that I try to get a response from the web request. Then it raises the first exception (unknown) and when I try to handle the error I get a second exception "Object reference not set to an instance of an object".
As far as I know normally what will cause this error is the attempt of getting a response of an unassigned web request, but in this case it IS assigned and the Uri is valid. All the credentials for authorization are correct too.
This is my code:
Try
Dim webRequest As System.Net.HttpWebRequest
webRequest = System.Net.HttpWebRequest.Create(InternalSettings.APIurl + "/config")
webRequest.Headers("Authorization") = InternalSettings.APIpwd
webRequest.Headers("API-Application-Key") = InternalSettings.APIkey
webRequest.Method = "PUT"
webRequest.ContentType = "application/x-www-form-urlencoded"
Dim postData As String = ""
postData += "SaveAllCustomersData=false"
Dim byteArray As Byte() = Encoding.UTF8.GetBytes(postData)
Dim dataStream As Stream = webRequest.GetRequestStream()
dataStream.Write(byteArray, 0, byteArray.Length)
dataStream.Close()
'The next line will raise an unknown exception
Dim myHttpWebResponse As HttpWebResponse = webRequest.GetResponse
Dim responseReader As StreamReader = New StreamReader(myHttpWebResponse.GetResponseStream())
Dim responseData As String = responseReader.ReadToEnd()
responseReader.Close()
webRequest.GetResponse().Close()
Catch ex As WebException
'The next line will raise a "Object reference not set to an instance of an object" exception
Dim resp = New StreamReader(ex.Response.GetResponseStream()).ReadToEnd()
Dim obj = JsonConvert.DeserializeObject(resp)
Return False
End Try
If you are using basic authentification you can try something like this:
Dim strUrl As String = InternalSettings.APIurl + "/config"
Dim request As WebRequest = DirectCast(WebRequest.Create(strUrl), HttpWebRequest)
Dim strResponse As String = ""
Dim byteAuth() As Byte = Encoding.UTF8.GetBytes(InternalSettings.APIkey & ":" & InternalSettings.APIpwd)
Dim strPost As String = "SaveAllCustomersData=false"
Dim bytePost() As Byte = Encoding.UTF8.GetBytes(strPost)
request.ContentType = "application/x-www-form-urlencoded"
request.Method = "PUT"
request.Headers.Add("Authorization", "Basic " & Convert.ToBase64String(byteAuth))
Using sw = New StreamWriter(request.GetRequestStream())
sw.Write(bytePost, 0, bytePost.Length)
sw.Flush()
Using response As HttpWebResponse = request.GetResponse()
Using sr = New StreamReader(response.GetResponseStream())
strResponse = sr.ReadToEnd()
End Using
End Using
End Using
I am not familiar a lot with Vb.Net, but I try to tweak something on an existent project. I have a cURL that try to implement on Vb.Net. I found different answers here and in other forums, but this way is the one I managed to reach
Private Function SendRequest(uri As Uri, jsonDataBytes As Byte(), contentType As String, method As String) As String
Dim req As WebRequest = WebRequest.Create(uri)
req.ContentType = contentType
req.Method = method
req.ContentLength = jsonDataBytes.Length
Dim stream = req.GetRequestStream()
stream.Write(jsonDataBytes, 0, jsonDataBytes.Length)
stream.Close()
Dim response = req.GetResponse().GetResponseStream()
Dim reader As New IO.StreamReader(response)
Dim res = reader.ReadToEnd()
reader.Close()
response.Close()
Return res
End Function
Dim postData As String = String.Format("text={0}", title)
Dim data = Encoding.UTF8.GetBytes(postData)
Dim uri = New Uri("https://.....")
Dim slackResponse = SendRequest(uri, data, "application/json", "POST")
And this is the error I get:
Exception Details: System.Net.WebException: The remote server returned an error: (400) Bad Request.
If I comment out the SendRequest function, I got an error during calling that, so I guess it is on that part.
Not able to debug more. Any ideas?
In order to debug more, you need to catch the WebException. WebExceptions have a response object that may contain more information.
Dim response as WebResponse
Try
response = req.GetResponse().GetResponseStream()
Catch ex As Net.WebException
If ex.Response IsNot Nothing Then
response = ex.Response
End If
End Try
This could be a problem with your URL parameters but many sites also return this class of error when there is a problem in the json content of the request.
I solved this long time ago by adding.
request.ContentType = "application/x-www-form-urlencoded"
I am trying to return a webpage as a stream.
What i have got so far works when i try and access an external url i.e. 'http://www.google.com'. But when i try and access a website on our server i.e. 'http://servername/applicationname/default.aspx'.
Below is the code that i currently have, that works for external :
Dim request As HttpWebRequest = CType(WebRequest.Create("http://www.google.com/search?q=google"), HttpWebRequest)
Dim response As HttpWebResponse = CType(request.GetResponse, HttpWebResponse)
Dim resStream As Stream = response.GetResponseStream
But when i try it with this line i get The remote server returned an error: (401) Unauthorized.
Dim request As HttpWebRequest = CType(WebRequest.Create("http://Server/Application/SubFolder/testing.aspx"), HttpWebRequest)
Dim response As HttpWebResponse = CType(request.GetResponse(), HttpWebResponse)
I have tried altering the credentials it accesses the server with using :
request.Credentials = CredentialCache.DefaultCredentials
And i have tried using a web client :
Dim myWebClient As New WebClient()
Dim myStream As Stream = myWebClient.OpenRead("http://Server/Application/SubFolder/testing.aspx")
You're getting the 401 error because the web server's authentication is rejecting the request. You may need to explicitly set your credentials.
request.Credentials = New NetworkCredential("userName", "password", "domain")
I've got a VB.NET app executing a simple WebRequest that is to interact with a web API. Through testing, I can successfully have the WebRequest executed and get a server response when I'm calling any static page on the server.
But when I execute a request of the API (which is interacting with a MySQL DB) the VB.NET app always throws this error:
The underlying connection was closed: An unexpected error occurred on
a send.
I do not get that error when I execute the same URL in a browser from the same PC. The API returns JSON encoded text with a text/plain content header.
Here is the VB.NET application code:
strURL = "https://soc-server.com/wireless/soc_wapi.php?&function=add_kb_event&logtype=33&datetime=2013-12-16%2013:50:50&kid=4&pid=1&peid=5&cid=97"
Dim ReturnValue As String = String.Empty
Dim Request As HttpWebRequest = CType(WebRequest.Create(New Uri(strURL)), HttpWebRequest)
Try
Dim ResponseText As String = String.Empty
Using Response As HttpWebResponse = CType(Request.GetResponse, HttpWebResponse)
Using ReceiveStream As Stream = Response.GetResponseStream
Using ReadStream As StreamReader = New StreamReader(ReceiveStream)
ReturnValue = ReadStream.ReadToEnd
processLog(ReturnValue)
End Using
End Using
End Using
Catch ex As Exception
processError(ex, "Error sending data")
End Try
I'm trying to authenticate my application using OAuth2 and using the 'installed applications' flow (get auth-code and then request token). I'm getting a 400 bad request error when requesting the token on the GetResponse() line. My code is as follows:
Public Sub New()
Dim tokenRequest As WebRequest =
WebRequest.Create("https://accounts.google.com/o/oauth2/token")
Dim requestString As String = "code=<auth-code>" _
& "&client_id=<client_id>" _
& "&client_secret=<client_secret>" _
& "&redirect_uri=http://localhost" _
& "&grant_type=authorization_code"
byteArray = StrToByteArray(System.Web.HttpUtility.UrlEncode(requestString))
tokenRequest.Credentials = CredentialCache.DefaultCredentials
tokenRequest.Method = "POST"
tokenRequest.ContentLength = byteArray.Length
tokenRequest.ContentType = "application/x-www-form-urlencoded"
Dim dataStream As Stream = tokenRequest.GetRequestStream()
dataStream.Write(byteArray, 0, byteArray.Length)
dataStream.Close()
Console.WriteLine("Getting response...")
'Get response
Try
Dim response As WebResponse = tokenRequest.GetResponse()
Console.WriteLine(CType(response, HttpWebResponse).StatusDescription)
Dim data As Stream = response.GetResponseStream
Array.Resize(byteArray, 4096)
Array.Clear(byteArray, 0, byteArray.Length)
data.Read(byteArray, 0, byteArray.Length)
response.Close()
Catch wex As WebException
Console.WriteLine("ERROR! : ")
Console.WriteLine(wex.Message)
Console.WriteLine(wex.Status)
Console.WriteLine(wex.Data)
Console.WriteLine(wex.InnerException.Message)
Console.WriteLine(wex.HelpLink)
End Try
End Sub
The specifics of the error are below:
The remote server returned an error: (400) Bad Request.
7
System.Collections.ListDictionaryInternal
System.NullReferenceException: Object reference not set to an instance of an obj
ect.
at GADownload.GoogleAnalytics..ctor() in ***.vb:line 86
at GADownload.Main1.Main(String[] args) in ****.vb:line 18
I've had a look at Google GetAccessToken : Bad Request 400 and Google GData .Net OAuthUtil.GetAccessToken 400 Bad Request but have not found a solution suited to this code. I have already checked all the solutions suggested and implemented them, but with no luck so far.
looks like you are not setting values for the parameters auth-code, client_id or client_secret.
you can debug these parameters with a curl command to see if this is the source of the problem. e.g.
curl -X POST -d "code=<auth-code>&client_id=<client_id>&client_secret=<client_secret>"&grant_type=authorization_code" http://localhost:8000/auth/token
Can you try URL encoding redirect_uri
redirect_uri=http://localhost
That is the only thing I'm seeing on your code vs. mine. Here's my code that is similar in vb and working
Dim sb As New StringBuilder
sb.Append("code=").Append(Request.QueryString("code")) _
.Append("&client_id=") _
.Append(Session.Item("ClientID")) _
.Append("&client_secret=") _
.Append(Session.Item("ClientSecret")) _
.Append("&redirect_uri=") _
.Append(HttpUtility.UrlEncode("http://localhost/1.aspx")) _
.Append("&grant_type=authorization_code")
Dim requestGoogle As HttpWebRequest =
WebRequest.Create("https://accounts.google.com/o/oauth2/token")
requestGoogle.Method = "POST"
requestGoogle.ContentType = "application/x-www-form-urlencoded"
requestGoogle.ContentLength = sb.Length
Dim byteArray As Byte() = Encoding.UTF8.GetBytes(sb.ToString)
sb.Clear()
requestGoogle.GetRequestStream.Write(byteArray, 0, byteArray.Length)
byteArray = Nothing
Dim responseGoogle As HttpWebResponse = requestGoogle.GetResponse()
If responseGoogle.StatusCode = HttpStatusCode.OK Then
Dim sr As StreamReader = _
New StreamReader(responseGoogle.GetResponseStream)
Dim s As String = sr.ReadToEnd
sr.Close()
responseGoogle.GetResponseStream.Close()
requestGoogle.GetRequestStream.Close()
'Response.Write(s)
End If