I am trying to POST some data from ASP.Net application to PHP using HttpWebRequest object. But when I try reading the Request content using
Stream myStream = myWebReq.GetRequestStream();
I am getting an error
'responseStream.Length' threw an exception of type 'System.NotSupportedException'.
Length = 'dataStream.Length' threw an exception of type 'System.NotSupportedException'
Position = 'dataStream.Position' threw an exception of type 'System.NotSupportedException'
Here is the code
string strURL = null;
HttpWebRequest myWebReq = default(HttpWebRequest);
HttpWebResponse myWebResp = default(HttpWebResponse);
byte[] byteData = null;
StreamReader sr = default(StreamReader);
strURL = "http://people.com.pk/nppm/hrms_ppm_service.php?dump=1";
myWebReq = (HttpWebRequest)WebRequest.Create(strURL);
myWebReq.ContentType = "application/x-www-form-urlencoded; charset=utf-8";
myWebReq.Method = "POST";
Label1.Text = Newtonsoft.Json.JsonConvert.SerializeObject(batches).ToString();
byteData = UTF8Encoding.UTF8.GetBytes(Label1.Text);
myWebReq.ContentLength = byteData.Length;
myWebReq.KeepAlive = true;
if (myWebReq.Proxy != null)
{
myWebReq.Proxy.Credentials = CredentialCache.DefaultCredentials;
}
Stream myStream = myWebReq.GetRequestStream();
if (byteData.Length > 0)
{
myStream.Write(byteData, 0, byteData.Length);
myStream.Close();
}
myWebResp = (HttpWebResponse)myWebReq.GetResponse();
sr = new StreamReader(myWebResp.GetResponseStream());
string strJSON__2 = sr.ReadToEnd();
Label1.Text = strJSON__2;
Just check your HttpWebRequest.DefaultCachePolicy property.
As the documentation suggest that HttpWebRequest.GetRequestStream method will throw NotSupportedException only when the request cache validator indicates that the response for the request can be served from the cache; however, requests that write data must not use the cache. This exception can occur if you are using a custom cache validator that is incorrectly implemented.
Related
I'm attempting to access a remote API and I'm getting a few exceptions during the HTTPWebResponse call. Below is my code:
//url
string responseValue = string.Empty;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("www.someapi.com")
request.Method = "GET";
request.UseDefaultCredentials = true;
request.ContentType = "application/json; charset=utf-8";
request.Headers("x-ms-client-id", "data");
try{
using (var response = (HttpWebRequest)req.GetResponse()){ <--- this line is the one that fails. System.IO.IOException here.
using (var stream = response.GetResponseStream()){
using(var sr = new StreamReader(stream)){
responseValue = sr.ReadToEnd();
}
}
}
} catch ///catch
The errors I'm getting are SocketExceptions and WebExceptions. I'm not sure why this specific call is failing. When I attempt the same URL and headers in Postman, the call returns a 200.
Any ideas would be appreciated.
EDIT:
Adding the error messages I'm getting. The exception being thrown when the response is attempted is
System.IO.IOException: "Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host."
Usually, I often use HttpWebRequest like below code.
You can download the HttpHelper I compiled and call it according to my reference example, or you can add Http Header as required.
How to invoke HttpHelper, ex: Get Method
Console app to use azure storage tableapi
String PostParam = String.Empty;
if (Data != null)
{
PostParam = Data.ToString();//Newtonsoft.Json.JsonConvert.SerializeObject(Data);
}
byte[] postData = Encoding.UTF8.GetBytes(PostParam);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri(url + (Id == null ? "" : '/' + Id.ToString())));
request.Method = Method;
request.ServicePoint.Expect100Continue = false;
request.Timeout = HttpRequestTimeOut;
request.ContentType = "application/json";
request.ContentLength = postData.Length;
if (postData.Length > 0)
{
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(postData, 0, postData.Length);
}
}
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
Response.Code = response.StatusCode;
using (StreamReader stream = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
{
Response.Data = stream.ReadToEnd();
}
}
I am doing an API Post request and cant seem to get it to work. I always get a sendFailure webexception and the response for the exception is always null so catching the exception is useless. It keeps happening when I try to get the httpWebResponse. I noticed too the request.contentlength gave errors at postream getrequeststream so i commented it out. Test.json is the file I use for the request body. I also tested this on different API testers by including the URL, body, and content-type in the header and they worked. I just cant seem to code it for myself. The credentials work I just dont know if im doing the request correctly?
JSON File:
{
"email": "abc#123.com",
"password": "12345",
"facilityNumber": "987654"
}
string filepath = "test.json";
string result = string.Empty;
using (StreamReader r = new StreamReader(filepath))
{
var json = r.ReadToEnd();
var jobj = JObject.Parse(json);
foreach (var item in jobj.Properties())
{
item.Value = item.Value.ToString().Replace("v1", "v2");
}
result = jobj.ToString();
Console.WriteLine(result);
}
try
{
string setupParameters;
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("https://www.test.com/abcde");
request.AllowAutoRedirect = true;
setupParameters = result;
ServicePointManager.ServerCertificateValidationCallback = (s, cert, chain, ssl) => true;
ASCIIEncoding encoding = new ASCIIEncoding();
var postData = setupParameters;
request.Method = "POST";
request.ContentType = "application/json";
byte[] data = encoding.GetBytes(postData);
//request.ContentLength = data.Length;
using (StreamWriter postStream = new StreamWriter(request.GetRequestStream()))//error if uncomment contentlength
{
postStream.Write(postData);
postStream.Flush();
postStream.Close();
}
HttpWebResponse wr = (HttpWebResponse)request.GetResponse();//error occurs
Stream receiveStream = wr.GetResponseStream();
StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8);
}
catch (WebException ex)
{
if (ex.Response != null)
{
using (var errorResponse = (HttpWebResponse)ex.Response)
{
using (var reader = new StreamReader(errorResponse.GetResponseStream()))
{
string error = reader.ReadToEnd();
result = error;
}
}
}
I suggest modifiying your request to follow this format. Especially pay attention to the request.Method and request.ContentType which have caught me out multiple times.
Also, handling the response is easier this way.
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(YOURURL);
request.ContentType = "application/json; charset=utf8";
request.Headers.Add(ADD HEADER HERE IF YOU NEED ONE);
request.Method = WebRequestMethods.Http.Post; // IMPORTANT
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
streamWriter.Write(JsonConvert.SerializeObject(JSONBODYSTRING));
// I USUALLY YOU JSONCONVERT HERE TO SIMPLY SERIALIZE A STRING CONTAINING THE JSON INFO.
//BUT I GUESS YOUR METHOD WOULD ALSO WORK
streamWriter.Flush();
streamWriter.Close();
}
WebResponse response = request.GetResponse();
using (var streamReader = new StreamReader(response.GetResponseStream()))
{
string result = streamReader.ReadToEnd();
// DO WHATEVER YOU'D LIKE HERE
}
} catch (Exception ex)
{
// HANDLE YOUR EXCEPTIONS
}
Here is my web request code block,
scroll down to the bottom of it to the catch exception
try
{
var webRequest = System.Net.WebRequest.Create (WEBSERVICE_URL);
if (webRequest != null) {
webRequest.Method = "POST";
//webRequest.Timeout = 12000;
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.Headers.Add ("Key", _apiKey);
webRequest.Headers.Add ("Sign", genHMAC ());
byte[] dataStream = Encoding.UTF8.GetBytes("command=returnBalances&nonce=" + nonce);
webRequest.ContentLength = dataStream.Length;
Stream newStream = webRequest.GetRequestStream();
newStream.Write(dataStream, 0, dataStream.Length);
newStream.Close();
using (System.IO.Stream s = webRequest.GetResponse ().GetResponseStream ()) {
using (System.IO.StreamReader sr = new System.IO.StreamReader (s)) {
var jsonResponse = sr.ReadToEnd ();
OutputText.text = jsonResponse.ToString ();
}
}
}
}
catch (Exception ex)
{
OutputText.text = ex.ToString ();
}
This gives me an "error(403) Forbidden" and the exception stack trace, but I am trying to get the 403 Response Body:
I cannot get Unity C# to accept the following code: mentioned here
catch(WebException ex)
{
var response = (HttpWebResponse)ex.Response;
}
What do I need to make this method work? I need the Response body
hmac.ToString() will not generate valid sign. To generate valid sign for Poloniex, you must use HMACSHA512.ComputeHash method and pass it dataStream as an argument. Bytes returned from this method then must be converted to hexadecimal string.
This should generate valid sign:
var hmac = new HMACSHA512(APISecret_Bytes);
var signBytes = hmac.ComputeHash(dataStream);
var sign = String.Join("", signBytes.Select(b => b.ToString("X2")));
Regarding WebException, it is declared in System.Net namespace, so make sure you have using System.Net;. Depending on target framework, WebException shoul be in System.Net.Requests.dll, System.dll, or netstandard.dll. Unfortunatelly I don't have any experience with Unity, but if my guess that it targets ordinary .NET Framework is correct, then WebException is declared in System.dll and your project should already have reference to it and no additional assembly reference should be needed.
I made a web application which translates the entered text into another language. I used Microsoft's Bing translator service for this and it works perfectly. But when i tried this in WPF application it gives an exception which is commented below. The exception says:
An unhandled exception of type'System.Runtime.Serialization.InvalidDataContractException' occurred in System.Runtime.Serialization.dll Additional information: Type 'TranslatorWPF.AdmAccessToken' cannot be serialized. Consider marking it with the DataContractAttribute attribute, and marking all of its members you want serialized with the DataMemberAttribute attribute. If the type is a collection, consider marking it with the CollectionDataContractAttribute.
Any help with this!!
Code
string clientID = "abc";
string clientSecret = "........";
String strTranslatorAccessURI = "https://datamarket.accesscontrol.windows.net/v2/OAuth2-13";
String strRequestDetails = string.Format("grant_type=client_credentials&client_id={0}&client_secret={1}&scope=http://api.microsofttranslator.com", HttpUtility.UrlEncode(clientID), HttpUtility.UrlEncode(clientSecret));
System.Net.WebRequest webRequest = System.Net.WebRequest.Create(strTranslatorAccessURI);
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.Method = "POST";
byte[] bytes = System.Text.Encoding.ASCII.GetBytes(strRequestDetails);
webRequest.ContentLength = bytes.Length;
using (System.IO.Stream outputStream = webRequest.GetRequestStream())
{
outputStream.Write(bytes, 0, bytes.Length);
}
System.Net.WebResponse webResponse = webRequest.GetResponse();
System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(AdmAccessToken));
//Get deserialized object from JSON stream
AdmAccessToken token = (AdmAccessToken)serializer.ReadObject(webResponse.GetResponseStream()); //** this line throws an exception
string headerValue = "Bearer " + token.access_token;
string txtToTranslate = text.Text;
string uri = "http://api.microsofttranslator.com/v2/Http.svc/Translate?text=" + System.Web.HttpUtility.UrlEncode(txtToTranslate) + "&from=en&to=ur";
System.Net.WebRequest translationWebRequest = System.Net.WebRequest.Create(uri);
translationWebRequest.Headers.Add("Authorization", headerValue);
System.Net.WebResponse response = null;
response = translationWebRequest.GetResponse();
System.IO.Stream stream = response.GetResponseStream();
System.Text.Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
System.IO.StreamReader translatedStream = new System.IO.StreamReader(stream, encode);
System.Xml.XmlDocument xTranslation = new System.Xml.XmlDocument();
xTranslation.LoadXml(translatedStream.ReadToEnd());
urdu.Text = xTranslation.InnerText;
I am implementing REST service and I am getting the above error. I searched a lot and used different methods to resolve this error but no luck. The service is working fine when I am using Postman or fiddler.
Here is my code :
try
{
string content = string.Empty;
var httpWebRequest = (HttpWebRequest)WebRequest.Create(new Uri("https://api.MYDOMAIN.com/servlet/Year"));
httpWebRequest.Method = "POST";
string parsedContent = "{\"securitykey\":\"KEY\"}";
var data = JObject.Parse(parsedContent);
Byte[] bytes = Encoding.UTF8.GetBytes(data.ToString());
httpWebRequest.ContentLength = bytes.Length;
httpWebRequest.ContentType = "application/json";
Stream newStream = httpWebRequest.GetRequestStream();
newStream.Write(bytes, 0, bytes.Length);
newStream.Close();
var response = (HttpWebResponse)httpWebRequest.GetResponse();
var stream = response.GetResponseStream();
if (stream != null)
{
var sr = new StreamReader(stream);
content = sr.ReadToEnd();
}
}
catch (WebException ex)
{
throw;
}
So in the above code I tried with :
httpWebRequest.ContentType = "application/x-www-form-urlencoded";
HttpUtility.UrlEncode()
I also tried the below code but it is giving me the same error :
using (var client = new WebClient())
{
client.Headers[HttpRequestHeader.ContentType] = "application/json";
result = client.UploadString("https://api.MYDOMAIN.com/servlet/Year", "POST", "{\"securitykey\":\"MYKEY\"}");
}
I added the security key in raw header as httpWebRequest.Headers.Add("{\"securitykey\":\"MYKEY\"}") but still no luck.
Really appreciate if I can get some help.
After a lot of RND I tried doing this in PHP, so it gave me an error as UserAgent is required. I added httpWebRequest.UserAgent and it worked. This error was never displayed in WebException.