Getting System.IO.IOException in mscorlib.dll - c#

i try to make an HTTP POST to an Swagger UI api and wrote this rudimentary Code:
string baseip = "192.168.0.1";
string auth = "authcodre";
string name = "TestMan";
string ip = "1.1.1.1";
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
string URL = "https://" + baseip + ":4444/api/objects/network/host/";
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(URL);
request.ContentType = "application/json";
request.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes("token:" + auth));
request.PreAuthenticate = true;
request.Method = "POST";
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
string patchtxt = "{ \"name\": \"" + name + "\", \"_type\": \"network/host\", \"address\": \"" + ip + "\"}";
streamWriter.Write(patchtxt);
streamWriter.Flush();
streamWriter.Close();
Console.WriteLine("Patches");
}
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
using (Stream responseStream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream, Encoding.UTF8); //Einlesen der HTTP-Antwort
string resppatch = reader.ReadToEnd();
Console.WriteLine(resppatch);
Console.ReadLine();
}
It throws me an System.IO.IOException" in mscorlib.dll at this line:
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(URL);
Can anyone explain why this happens and how to fix it?
Thank you :)

Related

How to fix The remote server returned an error: (403) Forbidden. dailymotion api

So I am using the Dailymotion API for uploading the video and use the code I get from the GitHub and it works perfectly but after 4 videos it gives the exception:
{"The remote server returned an error: (403) Forbidden."}
And I am getting an error in PublishVideo method
var response = request.GetResponse();
Main Code
var accessToken = GetAccessToken();
Authorize(accessToken);
Console.WriteLine("Access token is " + accessToken);
var fileToUpload = #"E:\Courses\[FreeCourseSite.com] Udemy - Entity Framework in Depth The Complete Guide\3. Building a Model using Database-First Workflow\11. Summary.mp4";
Console.WriteLine("File to upload is " + fileToUpload);
var uploadUrl = GetFileUploadUrl(accessToken);
Console.WriteLine("Posting to " + uploadUrl);
var response = GetFileUploadResponse(fileToUpload, accessToken, uploadUrl);
Console.WriteLine("Response:\n");
Console.WriteLine(response + "\n");
Console.WriteLine("Publishing video.\n");
var uploadedResponse = PublishVideo(response, accessToken);
Console.WriteLine(uploadedResponse);
Console.WriteLine("Done. Press enter to exit.");
Console.ReadLine();
}
private static UploadResponse GetFileUploadResponse(string fileToUpload, string accessToken, string uploadUrl)
{
var client = new WebClient();
client.Headers.Add("Authorization", "OAuth " + accessToken);
var responseBytes = client.UploadFile(uploadUrl, fileToUpload);
var responseString = Encoding.UTF8.GetString(responseBytes);
var response = JsonConvert.DeserializeObject<UploadResponse>(responseString);
return response;
}
private static UploadedResponse PublishVideo(UploadResponse uploadResponse, string accessToken)
{
var request = WebRequest.Create("https://api.dailymotion.com/me/videos?url=" + HttpUtility.UrlEncode(uploadResponse.url));
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.Headers.Add("Authorization", "OAuth " + accessToken);
var requestString = String.Format("title={0}&tags={1}&channel={2}&private={3}&published={4}",
HttpUtility.UrlEncode("123123123"),
HttpUtility.UrlEncode("tag1"),
HttpUtility.UrlEncode("news"),
HttpUtility.UrlEncode("true"),
HttpUtility.UrlEncode("true"));
var requestBytes = Encoding.UTF8.GetBytes(requestString);
var requestStream = request.GetRequestStream();
requestStream.Write(requestBytes, 0, requestBytes.Length);
var response = request.GetResponse();
var responseStream = response.GetResponseStream();
string responseString;
using (var reader = new StreamReader(responseStream))
{
responseString = reader.ReadToEnd();
}
var uploadedResponse = JsonConvert.DeserializeObject<UploadedResponse>(responseString);
return uploadedResponse;
}
private static string GetAccessToken()
{
var request = WebRequest.Create("https://api.dailymotion.com/oauth/token");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
var requestString = String.Format("grant_type=password&client_id={0}&client_secret={1}&username={2}&password={3}",
HttpUtility.UrlEncode(SettingsProvider.Key),
HttpUtility.UrlEncode(SettingsProvider.Secret),
HttpUtility.UrlEncode(SettingsProvider.Username),
HttpUtility.UrlEncode(SettingsProvider.Password));
var requestBytes = Encoding.UTF8.GetBytes(requestString);
var requestStream = request.GetRequestStream();
requestStream.Write(requestBytes, 0, requestBytes.Length);
var response = request.GetResponse();
var responseStream = response.GetResponseStream();
string responseString;
using (var reader = new StreamReader(responseStream))
{
responseString = reader.ReadToEnd();
}
var oauthResponse = JsonConvert.DeserializeObject<OAuthResponse>(responseString);
return oauthResponse.access_token;
}
private static void Authorize(string accessToken)
{
var authorizeUrl = String.Format("https://api.dailymotion.com/oauth/authorize?response_type=code&client_id={0}&scope=read+write+manage_videos+delete&redirect_uri={1}",
HttpUtility.UrlEncode(SettingsProvider.Key),
HttpUtility.UrlEncode(SettingsProvider.CallbackUrl));
Console.WriteLine("We need permissions to upload. Press enter to open web browser.");
Console.ReadLine();
Process.Start(authorizeUrl);
var client = new WebClient();
client.Headers.Add("Authorization", "OAuth " + accessToken);
Console.WriteLine("Press enter once you have authenticated and been redirected to your callback URL");
Console.ReadLine();
}
private static string GetFileUploadUrl(string accessToken)
{
var client = new WebClient();
client.Headers.Add("Authorization", "OAuth " + accessToken);
var urlResponse = client.DownloadString("https://api.dailymotion.com/file/upload");
var response = JsonConvert.DeserializeObject<UploadRequestResponse>(urlResponse).upload_url;
return response;
}
}
It could be related to many causes. I suggest you to catch the error and get the response stream from our API:
try{
var response = request.GetResponse();
var responseStream = response.GetResponseStream();
string responseString;
using (var reader = new StreamReader(responseStream))
{
responseString = reader.ReadToEnd();
}
var uploadedResponse = JsonConvert.DeserializeObject<UploadedResponse>(responseString);
return uploadedResponse;
}
catch(WebException e){
var rs = e.Response.GetResponseStream();
string errorResponseString;
using (var reader = new StreamReader(rs))
{
errorResponseString = reader.ReadToEnd();
}
Console.WriteLine(errorResponseString);
return null;
}
You will get a message explaining you why your access is forbidden.
I also invite you to check our API rate limit rules which can be a cause of forbidden call: https://developer.dailymotion.com/api/#rate-limit

Web API Authorization via HttpWebRequest

I have a function to call my Web API. It works well if TestCallingRemotely is set to [AllowAnonymous].
var httpWebRequest = (HttpWebRequest)WebRequest.Create(
"http://localhost/api/services/myApp/commonLookup/TestCallingRemotely");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream())) {
string input = "{}";
streamWriter.Write(input);
streamWriter.Flush();
streamWriter.Close();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
How do I pass the username and password to the HttpWebRequest for authorization?
I need to call my Web API from CLR integration, which only supports System.Net.
ABP's startup template uses bearer token authentication infrastructure.
var token = GetToken(username, password);
// var httpWebRequest = (HttpWebRequest)WebRequest.Create(
// "http://localhost/api/services/myApp/commonLookup/TestCallingRemotely");
// httpWebRequest.ContentType = "application/json";
// httpWebRequest.Method = "POST";
httpWebRequest.Headers.Add("Authorization", "Bearer " + token);
// ...
Get token
This uses a crude way to extract the token, inspired by an MSDN article.
private string GetToken(string username, string password, string tenancyName = null)
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create(
"http://localhost:6334/api/Account/Authenticate");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
var input = "{\"usernameOrEmailAddress\":\"" + username + "\"," +
"\"password\":\"" + password + "\"}";
if (tenancyName != null)
{
input = input.TrimEnd('}') + "," +
"\"tenancyName\":\"" + tenancyName + "\"}";
}
streamWriter.Write(input);
streamWriter.Flush();
streamWriter.Close();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
string response;
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
response = streamReader.ReadToEnd();
}
// Crude way
var entries = response.TrimStart('{').TrimEnd('}').Replace("\"", String.Empty).Split(',');
foreach (var entry in entries)
{
if (entry.Split(':')[0] == "result")
{
return entry.Split(':')[1];
}
}
return null;
}
If the server uses basic authentication you can add the header like this:
var httpWebRequest = (HttpWebRequest) WebRequest.Create(
"http://localhost/api/services/myApp/commonLookup/TestCallingRemotely");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
var username = "Aladdin";
var password = "opensesame";
var bytes = Encoding.UTF8.GetBytes($"{username}:{password}");
httpWebRequest.Headers.Add("Authorization", $"Basic {Convert.ToBase64String(bytes)}");
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string input = "{}";
streamWriter.Write(input);
streamWriter.Flush();
streamWriter.Close();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();

NetFramework convert to Net Core (HttpWebRequest)

I have a library for 4.5 net fw. I need do the same but for net core.
Big beer for person which can repair this..
Code from VS with errors (screen)
MY code:
string returnData = String.Empty;
var webRequest = HttpWebRequest.Create(url) as HttpWebRequest;
if (webRequest != null)
{
webRequest.Accept = "*/*";
webRequest.UserAgent = ".NET";
webRequest.Method = method;
webRequest.ContentType = "application/json";
webRequest.Host = "coinbase.com";
string nonce = Convert.ToInt64(DateTime.Now.Ticks).ToString();
string message = nonce + url;
string signature = HashEncode(HashHMAC(StringEncode(API_SECRET), StringEncode(message)));
var whc = new WebHeaderCollection();
whc.Add("ACCESS_KEY: " + API_KEY);
whc.Add("ACCESS_SIGNATURE: " + signature);
whc.Add("ACCESS_NONCE: " + nonce);
webRequest.Headers = whc;
using (WebResponse response = webRequest.GetResponse())
{
using (Stream stream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(stream);
returnData = reader.ReadToEnd();
}
}
}
You can use my code as below. Hope to help, my friend:
var webRequest = WebRequest.Create(url) as HttpWebRequest;
if (webRequest != null)
{
webRequest.Accept = "*/*";
webRequest.UserAgent = ".NET";
webRequest.Method = WebRequestMethods.Http.Post;
webRequest.ContentType = "application/json";
webRequest.Host = "coinbase.com";
var whc = new WebHeaderCollection
{
"ACCESS_KEY: " + API_KEY,
"ACCESS_SIGNATURE: " + signature,
"ACCESS_NONCE: " + nonce
};
webRequest.Headers = whc;
using (WebResponse response = webRequest.GetResponse())
{
using (Stream stream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(stream);
returnData = reader.ReadToEnd();
}
}
}

HttpWebRequest - payload error

HttpWebRequest Request = (HttpWebRequest)WebRequest.Create(url);
Request.Headers.Add("Authorization", "OAuth " + GetAccessTokenBeta());
Request.Proxy.Credentials = CredentialCache.DefaultCredentials;
Request.Method = "POST";
Request.ContentType = "application/xml";
using (var streamWriter = new StreamWriter(Request.GetRequestStream()))
{
string xml = getXml(tabletype, values.ToArray());
streamWriter.Write(xml);
streamWriter.Flush();
streamWriter.Close();
}
try
{
using (WebResponse response = Request.GetResponse())
{
using (StreamReader rd = new StreamReader(response.GetResponseStream()))
{
}
}
}
catch (WebException ex)
{
var resp = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();
Core.ShowError("Error connecting to the webservice." + "\r\n" + resp);
}
I have confirmed that the endpoint and XML work using Postman, but I am running into this issue in C#.
Error sending HTTP request. Message payload is of type: BufferInputStream

POST request to REST API with JSON object as payload in UNITY Getting ERROR

I am calling an API but its giving me below error:
UriFormatException: Absolute URI is too short
Please check below code:
void updatePlayer ()
{
HttpWebRequest httpWebRequest = WebRequest.Create (requestURL) as HttpWebRequest;
httpWebRequest.ContentType = "application/x-www-form-urlencoded";
httpWebRequest.Method = "POST";
httpWebRequest.Headers.Add ("x-api-key", "e1Zdd1YD92aJtpyDaCtSDTZCrDXtv2c9Cf");
string json = "{" +
"'firstName': '100'," +
"'lastName': 'DEF'" +
"}";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream())) {
streamWriter.Write (json);
}
httpWebRequest.ContentLength = json.Length;
HttpWebResponse httpResponse = (HttpWebResponse)httpWebRequest.GetResponse ();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream())) {
var responseText = streamReader.ReadToEnd ();
//Now you have your response.
//or false depending on information in the response
Debug.Log (responseText);
}
}

Categories

Resources