C# 405 methods not allowed - c#

I am posting data to a website and displaying the resulting json data,
This is the function I ended up with after taking some pieces from msdn's example
private string request(string url, string data)
{
byte[] byteArray;
string postData,
responseFromServer;
WebResponse response;
Stream dataStream;
StreamReader reader;
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.Proxy = new WebProxy(ip, port);
responseFromServer = string.Empty;
request.Method = "POST";
request.Timeout = 10000;
postData = data;
byteArray = Encoding.UTF8.GetBytes(postData);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteArray.Length;
try
{
dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
response = request.GetResponse();
dataStream = response.GetResponseStream();
reader = new StreamReader(dataStream);
responseFromServer = reader.ReadToEnd();
reader.Close();
dataStream.Close();
response.Close();
}
catch (Exception x)
{
x.ToString();
}
return responseFromServer;
}
}
The ip and port variables are within the class that this function is inside of.
When GetResponse() is called, it this exception.
{System.Net.WebException: The remote server returned an error: (405) Method Not Allowed.
Ive tested it and it is only because of the proxy, but the parameters are correct.
Why is this exception being thrown?

Related

c# How to send HTTP command as this - http://192.168.10.1/api/control?alert=101002

I have this hardware from Patlite,
This hardware has an HTTP command control function, for example, if I copy the url "http://192.168.10.1/api/control?alert=101002" to chrome in my computer, it will activate the hardware as needed.
I want to send the command from my code.
I tried this code with no luck:
System.Net.ServicePointManager.Expect100Continue = false;
WebRequest request = WebRequest.Create("http://10.0.22.222/api/control");
request.Method = "post";
request.ContentType = "application/x-www-form-urlencoded";
string postData = "alert=101002";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
request.ContentLength = byteArray.Length;
// Get the request stream.
Stream dataStream = request.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close();
WebResponse response = request.GetResponse();
There is a picture from the manual:
Thanks
You need to create a webrequest instance for this.
WebRequest request = WebRequest.Create("http://192.168.10.1/api/control?alert=101002");
WebResponse response = request.GetResponse();
You may need to set some properties as request method and credentials for this to work.
See this:
https://msdn.microsoft.com/en-us/library/456dfw4f(v=vs.100).aspx
public static string Get(string url, Encoding encoding)
{
try
{
var wc = new WebClient { Encoding = encoding };
var readStream = wc.OpenRead(url);
using (var sr = new StreamReader(readStream, encoding))
{
var result = sr.ReadToEnd();
return result;
}
}
catch (Exception e)
{
//throw e;
return e.Message;
}
}
like this code use the url "http://192.168.10.1/api/control?alert=101002" to send get request.Good luck!

The magic number in GZip header is not correct. Make sure you are passing in a GZip stream getting this error

i am working on asp.net webform to passing json string on a url for authenticate but getting error in Gzip.
here is my method to post data
private static string GetResponse(string requestData, string url)
{
string responseXML = string.Empty;
try
{
byte[] data = Encoding.UTF8.GetBytes(requestData);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "application/json";
request.Headers.Add("Accept-Encoding", "gzip");
Stream dataStream = request.GetRequestStream();
dataStream.Write(data, 0, data.Length);
dataStream.Close();
WebResponse webResponse = request.GetResponse();
var rsp = webResponse.GetResponseStream();
if (rsp == null)
{
//throw exception
}
using (StreamReader readStream = new StreamReader(new GZipStream(rsp, CompressionMode.Decompress)))
{
responseXML = JsonConvert.DeserializeXmlNode(readStream.ReadToEnd()).InnerXml;
}
}
catch (WebException webEx)
{
//get the response stream
WebResponse response = webEx.Response;
Stream stream = response.GetResponseStream();
String responseMessage = new StreamReader(stream).ReadToEnd();
}
finally
{
}
return responseXML.ToString();
}
getting this error while i am passing the json object and url
enter image description here

HttpWebRequest webservice call returns Request format is invalid: text/xml;charset=UTF-8

Trying to call WebService using HTTPWebRequest and posting data, it results in invalid request format, I have added http verbs post in both client and webservice, any ideas here ?
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://localhost/WS/test.asmx/GetData");
String xmlString = "Montreal";
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] bytesToWrite = encoding.GetBytes(xmlString);
request.Method = "POST";
request.ContentLength = bytesToWrite.Length;
request.ContentType = "text/xml;charset=UTF-8";
Stream newStream = request.GetRequestStream();
newStream.Write(bytesToWrite, 0, bytesToWrite.Length);
newStream.Close(); //fails here with error message Request format is invalid: text/xml;charset=UTF-8.
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
Console.WriteLine(responseFromServer);
I got to modify the approach, this worked for me.
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://localhost/WS/test.asmx");
String xmlData = "Montréal";
String xmlString = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:tem=\"http://tempuri.org/\"><soapenv:Header/> <soapenv:Body><tem:GetData><tem:data>" + xmlData + "</tem:data></tem:GetData></soapenv:Body></soapenv:Envelope>";
byte[] bytesToWrite = Encoding.UTF8.GetBytes(xmlString);
request.Method = "POST";
request.ContentLength = bytesToWrite.Length;
request.ContentType = "text/xml;charset=UTF-8;";
Stream newStream = request.GetRequestStream();
newStream.Write(bytesToWrite, 0, bytesToWrite.Length);
newStream.Close();
try
{
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
Console.WriteLine(responseFromServer);
}
catch (Exception ex)
{
string msg = ex.Message;
}

Unable to consume POST method of OpenShift REST based API

I am trying to create application into OpenShift Red hat environment from my sample code which I have developed in C#.net.
string url =string.Format("https://openshift.redhat.com/broker/rest/domain/{0}/applications", cbDomains.Text);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.Credentials = new NetworkCredential(USERNAME, PASSWORD);
string postData = "{\"name\": \"myapp\","
+ "\"cartridges\": [{"
+ "\"cartridge\": \"diy-0.1\"}],"
+ "\"scale\": false,"
+ "\"gear_size\": \"small\"}";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
request.ContentType = "application/x-www-form-urlencoded;";
request.ContentLength = byteArray.Length;
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
WebResponse response = request.GetResponse();
dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
reader.Close();
dataStream.Close();
response.Close();
when I am executing above code I am getting following error:
The remote server returned an error: (422) Unprocessable Entity.
on this below line:
WebResponse response = request.GetResponse();
Please let me where I am doing wrong. Thanks in advance Jyoti

HttpWebRequest doesn't work every time

I'm doing a WebRequest to a Uri but the problem is that I don't get a response every time. Sometimes I need to redo it. I would like my program to check if it got no response and if so the program will automatically recall the method for the WebRequest until I get a response.
In pseudocode
while(response == null)
{
try it again
}
This is my function. The capital comment is the explanation of my issue
private string HttpWebRequest()
{
string xml = #"<?xml version='1.0' encoding='UTF-8' standalone='yes'?>
<Siri version='1.0' xmlns='http://www.siri.org.uk/'>
<ServiceRequest>
<RequestTimestamp>2011-10-24T15:09:12Z</RequestTimestamp>
<RequestorRef><USERNAME></RequestorRef>
<StopMonitoringRequest version='1.0'>
<RequestTimestamp>2011-10-24T15:09:12Z</RequestTimestamp>
<MessageIdentifier>12345</MessageIdentifier>
<MonitoringRef>020035811</MonitoringRef>
</StopMonitoringRequest>
</ServiceRequest>
</Siri>";
string responseFromServer = null;
WebRequest request = WebRequest
.Create("http://<USERNAME>:<PASSWORD>#nextbus.mxdata.co.uk/nextbuses/1.0/1");
request.Method = "POST";
string postData = xml;
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteArray.Length;
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
////////IF I GET NO RESPONSE EVERYTHING AFTER THE NEXT LINE WILL BE IGNORED
WebResponse response = request.GetResponse();
///////////THIS MESSAGEBOX WILL BE IGNORED
MessageBox.Show(((HttpWebResponse)response).StatusDescription+" Completed");
dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
responseFromServer = reader.ReadToEnd();
reader.Close();
dataStream.Close();
response.Close();
return responseFromServer;
}
How can I resolve this?
If you want to just retry if the returned result ends up being null.. why not just do something like:
private void RunWebrequest()
{
if (HttpWebRequest() == null)
{
RunWebrequest();
}
else
{
//continue
}
}
I had the same 401 issue with this server, instead of placing your username & password in the url as per the traveline documentation use "Credentials" instead:-
string travelineUrl = "http://nextbus.mxdata.co.uk/nextbuses/1.0/1";
var travelineRequest = (HttpWebRequest)WebRequest.Create(travelineUrl);
travelineRequest.Credentials = new NetworkCredential("yourusername", "yourpassword");

Categories

Resources