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.
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 trying to send JSON Object to Server for data synchronization.
This JSON object contain non-synchronized images and their data.
Real problem is not with he JSON or the Synchronization code.
But it is with the size of the Request i am sending to the server.
if the size cross the limit 1.1MB then i Got this message
The remote server returned an error: (413) Request Entity Too Large.
Please Help me. It is pur C# application not the WCF application.
Domain Hosting provider is Godady.com.
Using Apache server and PHP script.
Every this is working fine for smaller size. but it give exception error when size cross 1.1MB.
Here is My Request Code.
public string SubmitData(string poststring)
{
string result ="false";
if (poststring.ToLower() == "empty")
{
result = "empty";
return result;
}
try
{
ASCIIEncoding encoding = new ASCIIEncoding();
string postData = poststring;
byte[] data = encoding.GetBytes(postData);
WebRequest request = WebRequest.Create("http://blunor.com/dark/data.php");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.Credentials = CredentialCache.DefaultCredentials;
request.ContentLength = data.Length;
Stream stream = request.GetRequestStream();
showMessageBox(data.Length.ToString(), "Message", 1);
stream.Write(data, 0, data.Length);
stream.Close();
WebResponse response = request.GetResponse();
stream = response.GetResponseStream();
StreamReader sr = new StreamReader(stream);
// this block of code check if response is +ve or negtive..
string res_num = sr.ReadToEnd();
if (res_num == "1")
{
result = "true";
}
else
{
result = "false";
}
//block end here.....
sr.Close();
stream.Close();
return result;
}
catch (Exception ex)
{
MessageBox.Show("Error : " + ex.Message);
}
return result;
}
For Server php post_max_size = 128M and Upload_max_filesize = 32M
Please Help......
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.
I have read other similar questions and tried the solutions from those questions, but since that did not work, hence I am posting this here.
When I send POST request below, it fails with the following error message:
System.Net.ProtocolViolationException: You must write ContentLength bytes to the request stream before calling [Begin]GetResponse.
at System.Net.HttpWebRequest.GetResponse()
....
....
My GET requests for other URL end points are working fine, I am only having this issue while issuing a POST request. Also, I have already set the ContentLength in the code appropriately. I am still unable to send the POST request. Thoughts?
public void TestSubmitJobWithParams1()
{
const string RestActionPath = "URL_GOES_HERE";
// if you have multipe parameters seperate them with teh '&' delimeter.
var postData = HttpUtility.UrlEncode("MaxNumberOfRowsPerSFSTask") + "=" + HttpUtility.UrlEncode("3000");
var request = (HttpWebRequest)WebRequest.Create(RestActionPath);
request.Method = "POST";
request.Credentials = CredentialCache.DefaultCredentials;
request.PreAuthenticate = true;
request.ContentLength = 0;
request.Timeout = 150000;
request.CachePolicy = new RequestCachePolicy(RequestCacheLevel.BypassCache);
request.ContentType = "application/x-www-form-urlencoded";
byte[] bytes = Encoding.ASCII.GetBytes(postData);
request.ContentLength = bytes.Length;
Stream newStream = request.GetRequestStream();
newStream.Write(bytes, 0, bytes.Length);
string output = string.Empty;
try
{
using (var response = request.GetResponse())
{
using (var stream = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(1252)))
{
output = stream.ReadToEnd();
}
}
}
catch (WebException ex)
{
if (ex.Status == WebExceptionStatus.ProtocolError)
{
using (var stream = new StreamReader(ex.Response.GetResponseStream()))
{
output = stream.ReadToEnd();
}
}
else if (ex.Status == WebExceptionStatus.Timeout)
{
output = "Request timeout is expired.";
}
}
catch (ProtocolViolationException e)
{
Console.WriteLine(e);
}
Console.WriteLine(output);
Console.ReadLine();
}
A few things:
Firstly, you don't need to set ContentLength directly - just leave it out (defaults to -1). You're actually calling it twice, so remove both calls.
Also, you need to call Close() on the stream before calling GetResponse()
Stream newStream = request.GetRequestStream();
newStream.Write(bytes, 0, bytes.Length);
newStream.Close();
Alternatively, you could have it within a using statement, which handles the closing and disposal for you):
using (var newStream = request.GetRequestStream())
{
newStream.Write(bytes, 0, bytes.Length);
}
You also don't technically need to use HttpUtility.UrlEncode() for the postData since there's nothing in your string that would violate a Url's integrity. Just do:
string postData = "MaxNumberOfRowsPerSFSTask=3000");
Let me know if that solves it for you.
For a more thorough rundown, check this out: http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.getresponse.aspx
Specifically, the section about ProtocolViolationException and also where it says:
When using the POST method, you must get the request stream, write the data to be posted, and close the stream. This method blocks waiting for content to post; if there is no time-out set and you do not provide content, the calling thread blocks indefinitely.
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.