System.Net.WebException - Internal Server error 500 - c#

While I am doing a web API using C# console Application using HttpWebRequest an exception occurs
The remote server returned an error: (500) Internal Server Error.
Here is my code:
string postURL = "";
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(postURL);
webRequest.Method = "POST";
webRequest.Headers.Add("token", "ee22c61a55bd0629c8c8a63a8c8b73ed");
webRequest.KeepAlive = true;
webRequest.ContentType = "application/json";
webRequest.Headers.Add("ContentType","application/json");
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int byteCount = 0;
FileInfo finfo = new FileInfo(#"D:\audio\smallwave.zip");
webRequest.ContentLength = finfo.Length;
// webRequest.SendChunked = true;
using (FileStream fileStream = File.OpenRead(#"D:\audio\smallwave.zip"))
using (Stream requestStream = webRequest.GetRequestStream())
{
while ((byteCount = fileStream.Read(buffer, 0, bufferSize)) > 0)
{
requestStream.Write(buffer, 0, byteCount);
}
}
HttpWebResponse httpResponse = (HttpWebResponse)webRequest.GetResponse();
// using (WebResponse response = webRequest.GetResponse())
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
String result = streamReader.ReadToEnd();
Console.WriteLine(result);
}
An error is showing like
An unhandled exception of type 'System.Net.WebException' occurred in
System.dll
Additional information: The remote server returned an error: (500)
Internal Server Error.

using HTTPClient
string baseUrl = "https://vspark-demo.vocitec.com/transcribe/M2ComSys-Pilot/eng1CCStereo/";
HttpClient client = new HttpClient();
MultipartFormDataContent form = new MultipartFormDataContent();
HttpContent content = new StringContent("file");
HttpContent DictionaryItems = new FormUrlEncodedContent(new[] {
new KeyValuePair<string, string>("token", "ee22c61a55bd0629c8c8a63a8c8b73ed"),
});
form.Add(content, "files");
// form.Add(DictionaryItems, "data");
form.Add(new StringContent("ee22c61a55bd0629c8c8a63a8c8b73ed"), "token");
var stream = new FileStream(#"D:\audio\variety.wav", FileMode.Open);
content = new StreamContent(stream);
content.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
{
Name = "file",
FileName = "variety.wav"
};
form.Add(content);
HttpResponseMessage response = null;
try
{
response = (client.PostAsync(baseUrl, form)).Result;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.WriteLine(response);
var k = response.Content.ReadAsStringAsync().Result;
Console.WriteLine(k);
Console.ReadLine();
}

Related

post httpwebrequest to channel advisor

I am trying to get new token from channeladvisor ecommerce
I am using this code
// HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://api.channeladvisor.com/oauth2/token");
var request=HttpWebRequest.Create("https://api.channeladvisor.com/oauth2/token");
WebResponse response = null;
string responseString = string.Empty;
try
{
// request.Timeout = 300000;
// request.KeepAlive = false;
//request.ContentType = "application/json";
request.UseDefaultCredentials = true;
string credentials = applicationid + ":" + sharesecret;
byte[] bytes = System.Text.Encoding.ASCII.GetBytes(credentials);
string base64 = Convert.ToBase64String(bytes);
request.Headers["Authorization"] = "Basic " + base64;
request.ContentType = " application/x-www-form-urlencoded";
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11 |
SecurityProtocolType.Tls12;
request.Method = "Post";
// var stringContent = new StringContent("grant_type=refresh_token&refresh_token=" + refreshToken);
request.ContentLength = System.Text.Encoding.ASCII.GetByteCount("grant_type=refresh_token&refresh_token=" + refreshToken);
byte[] buffer = System.Text.Encoding.ASCII.GetBytes("grant_type=refresh_token&refresh_token=" + refreshToken);
// string result = System.Convert.ToBase64String(buffer);
Stream reqstr = request.GetRequestStream();
reqstr.Write(buffer, 0, buffer.Length);
reqstr.Close();
response = (HttpWebResponse)request.GetResponse();
using (Stream responseStream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream);
responseString = reader.ReadToEnd();
}
}
catch (Exception)
{
throw;
}
but I keep getting the error
System.Net.WebException: The request was aborted: Could not create SSL/TLS secure channel.
what is problem? thank you
Try this Added this line:-
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
// Use SecurityProtocolType.Ssl3 if needed for compatibility reasons
Refer More From Here which help you alot

Rest Client Authorization error

I want to call a rest client with basic authorization. I tried this but got a Unauthorized(401) exception in c# :
HttpWebRequest client = (HttpWebRequest)WebRequest.Create("http://someurl.com");
client.Method = "POST";
client.UseDefaultCredentials = true;
var encoding = new UTF8Encoding();
var bytes = Encoding.GetEncoding("iso-8859-1").GetBytes(mailinglist.ToString());
client.ContentLength = bytes.Length;
using (var writeStream = client.GetRequestStream())
{
writeStream.Write(bytes, 0, bytes.Length);
}
client.ContentType = "application/json";
NetworkCredential nc = new NetworkCredential("8ec5f23e-18ba-4154-9962-7ebefeb027c0", "");
//string credentials = String.Format("{0}:{1}", "8ec5f23e-18ba-4154-9962-7ebefeb027c0", "");
//byte[] bts = Encoding.ASCII.GetBytes(credentials);
//string base64 = Convert.ToBase64String(bts);
client.PreAuthenticate = true;
//string authorization = String.Concat("Basic ", base64);
//Utils.WriteLog("Addaudience", authorization);
//client.Headers.Add(HttpRequestHeader.Authorization, authorization);
client.Credentials = nc;
client.Accept = "application/json";
using (var response = (HttpWebResponse)client.GetResponse())
{
var responseValue = string.Empty;
if (response.StatusCode != HttpStatusCode.OK)
{
var message = String.Format("Request failed. Received HTTP {0}", response.StatusCode);
throw new ApplicationException(message);
}
// grab the response
using (var responseStream = response.GetResponseStream())
{
if (responseStream != null)
using (var reader = new StreamReader(responseStream))
{
responseValue = reader.ReadToEnd();
}
}
}
Please help me and tell me what is my mistake? I also tried to put Authorization string in the headers but not working.
Thanks.

Login into iCloud via Json Post request

I'm trying to log in into iCloud using a Json Post request in C#. Before trying to implement the code I was studying a little bit the iCloud requests using Chrome Console and using an Ad-on to replicate the requests in order to obtain the same result of the website.
First of All I checked the request directly from iCloud website:
And this is the response:
{
"serviceErrors" : [ {
"code" : "-20101",
"message" : "Il tuo IDĀ Apple o la password non sono corretti."
} ]
}
Using "Advance REST Client" ad Chrome plugin to replicate the request I ve tried the same Json request to the same Url. But I get Empty response:
I Also tried to copy and paste the whole Header (All the settings) and than send the request but the response is the same:
Anyone has an Advice?
UPDATE: I tried to implement A Json request through c# program:
var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://idmsa.apple.com/appleauth/auth/signin");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = "{accountName: \"briesanji #gmail.com\", password: \"testPassword\", rememberMe: false, trustTokens: []}";
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
The problem is that Execution breaks when the
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
is hit and it gives me this error: System.Net.WebException: 'Error Remote Server: (400) Request not valid.'
UPDATE: I solved in this way:
void POST(string url, string jsonContent)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
Byte[] byteArray = encoding.GetBytes(jsonContent);
request.ContentLength = byteArray.Length;
request.ContentType = #"application/json";
using (Stream dataStream = request.GetRequestStream())
{
dataStream.Write(byteArray, 0, byteArray.Length);
}
long length = 0;
try
{
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
length = response.ContentLength;
}
}
catch (WebException ex)
{
// Log exception and throw as for GET example above
}
}
string GET(string url)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
try
{
WebResponse response = request.GetResponse();
using (Stream responseStream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
return reader.ReadToEnd();
}
}
catch (WebException ex)
{
WebResponse errorResponse = ex.Response;
using (Stream responseStream = errorResponse.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8"));
String errorText = reader.ReadToEnd();
// log errorText
}
throw;
}
}
Anyways I tested also the Answer and it was good to.. So I check it as valid thanks.
With this i dont get any error and the response content of the second request just tells me that there were too many failed logins for the test account...
private static void ICloud()
{
var cc = new CookieContainer();
var first = (HttpWebRequest)WebRequest.Create("https://idmsa.apple.com/appleauth/auth/signin?widgetKey=83545bf919730e51dbfba24e7e8a78d2&locale=de_DE&font=sf");
first.Method = "GET";
first.CookieContainer = cc;
var response1 = (HttpWebResponse)first.GetResponse();
using (var streamReader = new StreamReader(response1.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
var second = (HttpWebRequest)WebRequest.Create("https://idmsa.apple.com/appleauth/auth/signin");
second.ContentType = "application/json";
second.Method = "POST";
second.Accept = "application/json";
second.CachePolicy = new RequestCachePolicy(RequestCacheLevel.NoCacheNoStore);
second.Referrer = "https://idmsa.apple.com/appleauth/auth/signin?widgetKey=83545bf919730e51dbfba24e7e8a78d2&locale=de_DE&font=sf";
second.Headers.Add("X-Requested-With", "XMLHttpRequest");
second.Headers.Add("X-Apple-Widget-Key", "83545bf919730e51dbfba24e7e8a78d2");
using (var streamWriter = new StreamWriter(second.GetRequestStream()))
{
string json = "{\"accountName\":\"test#icloud.com\",\"password\":\"test\",\"rememberMe\":false,\"trustTokens\":[]}";
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}
try
{
var response2 = (HttpWebResponse)second.GetResponse();
using (var streamReader = new StreamReader(response2.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
}
catch(WebException we)
{
using (var r = new StreamReader(we.Response.GetResponseStream()))
{
var result2 = r.ReadToEnd();
}
}
}

submit attachment using HttpWebRequest

I'm trying to submit an attachment to a REST API. attachment is not submitted correctly. I believe that i'm doing something wrong with the request
RunQueryimage("http://www.extremetech.com/wp-content/uploads/2012/12/Audi-A1.jpg);
public string RunQueryimage(string imagePath)
{
//do get request
HttpWebRequest request = (HttpWebRequest)
WebRequest.Create("https://iss.ontimenow.com/api/v2/incidents/");
request.ContentType = "application/octet-stream";
request.Method = "POST";
var webClient = new WebClient();
byte[] bytearr = webClient.DownloadData(imagePath);
var filecontent = new ByteArrayContent(bytearr);
// request.ContentLength = 0;
if (filecontent != null)
{
using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))
{
writer.Write(filecontent);
}
}
HttpWebResponse response = (HttpWebResponse)
request.GetResponse();
string result = string.Empty;
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
result = reader.ReadToEnd();
}
return result;
}
You already have a stream open when you create a web request.
Change this:
byte[] bytearr = webClient.DownloadData(imagePath);
var filecontent = new ByteArrayContent(bytearr);
// request.ContentLength = 0;
if (filecontent != null)
{
using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))
{
writer.Write(filecontent);
}
}
To:
byte[] fileContent = webClient.DownloadData(imagePath);
if (fileContent != null)
{
Stream requestStream = request.GetRequestStream();
requestStream.Write(fileContent, 0, fileContent.Length);
requestStream.Close();
}

The request was aborted: The connection was closed unexpectedly

I am using Jon Skeet's ReadFully method implemented here:
public static byte[] ReadFully(Stream stream)
{
var buffer = new byte[32768];
using (var ms = new MemoryStream())
{
while (true)
{
int read = stream.Read(buffer, 0, buffer.Length);
if (read <= 0)
return ms.ToArray();
ms.Write(buffer, 0, read);
}
}
}
It throws an exception at the line:
int read = stream.Read(buffer, 0, buffer.Length);
The error message is The request was aborted: The connection was closed unexpectedly.
I am sending an xml request to a webservice. My send method looks like this:
private static string SendRequest(XElement request, string url)
{
var req = (HttpWebRequest)WebRequest.Create(url);
req.ContentType = "application/soap+xml;";
req.Method = "POST";
req.KeepAlive = false;
req.Timeout = System.Threading.Timeout.Infinite;
req.ReadWriteTimeout = System.Threading.Timeout.Infinite;
req.ProtocolVersion = HttpVersion.Version10;
req.AllowWriteStreamBuffering = false;
using (var stm = req.GetRequestStream())
{
using (var stmw = new StreamWriter(stm))
{
stmw.Write(request.ToString());
}
}
Stream responseStream;
using (var webResponse = req.GetResponse())
{
responseStream = webResponse.GetResponseStream();
}
// Do whatever you need with the response
var myData = ReadFully(responseStream);
string responseString = Encoding.ASCII.GetString(myData);
return responseString;
}
I tried without and without the following variables set and it gives me the same message:
req.KeepAlive = false;
req.Timeout = System.Threading.Timeout.Infinite;
req.ReadWriteTimeout = System.Threading.Timeout.Infinite;
req.ProtocolVersion = HttpVersion.Version10;
req.AllowWriteStreamBuffering = false;
The problem is in this part of your code:
// wrong way to do it!
Stream responseStream;
using (var webResponse = req.GetResponse())
{
responseStream = webResponse.GetResponseStream();
}
// Do whatever you need with the response
var myData = ReadFully(responseStream);
You're disposing your response object before reading from its stream. Try something like this instead:
byte[] myData;
using (var webResponse = req.GetResponse())
{
var responseStream = webResponse.GetResponseStream();
myData = ReadFully(responseStream); // done with the stream now, dispose of it
}
// Do whatever you need with the response
string responseString = Encoding.ASCII.GetString(myData);

Categories