Text API intergration issue - Error 405 page not found - c#

I am using Innovative Text SMS API gateway which is through me error.
Documentation is available at link http://www.innovativetxt.com/services/sms_api_gateway.htm, the error is happening on my local machine, but works fine at the production server.
The remote server returned an error: (405) Method Not Allowed.
at this line of code:
HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();
try
{
// InnovativeTXT POST URL
string url = "http://innovativetxt.com/cp/api";
// XML-formatted data
string toSender = "4477878585244";
string fromSender = "Test";
string textMessage = "Thanks for Choosing Innovative Text Messaging Solution.";
string fields = "?to=" + toSender + "&from=" + fromSender + "&text=" + textMessage + "&api_key=xxx&api_secret=xxxxx";
url = url + fields;
// web request start
Uri uri = new Uri(url);
string data = "field-keywords=ASP.NET 2.0";
if (uri.Scheme == Uri.UriSchemeHttp)
{
// create a request on behalf of uri
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
// setting parameter for the request
request.Method = WebRequestMethods.Http.Post;
request.ContentLength = data.Length;
request.ContentType = "application/x-www-form-urlencoded";
// a stream writer for the request
StreamWriter writer = new StreamWriter(request.GetRequestStream());
// write down the date
writer.Write(data);
//close the stream writer
writer.Close();
// getting response from the request
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
// Get the stream associated with the response.
Stream receiveStream = response.GetResponseStream();
// Pipes the stream to a higher level stream reader with the required encoding format.
StreamReader readStream = new StreamReader(receiveStream, System.Text.Encoding.UTF8);
// to write a http response from the characters
Response.Write(readStream.ReadToEnd());
// close the response
response.Close();
// close the reader
readStream.Close();
}
}
catch (Exception exp)
{
// catch for unhelded exception
Response.Write(exp.Message);
}

This issue relates to IIS Handler mappings.
You should specify the file name at the end of string URL:
string url = "http://innovativetxt.com/cp/api/somepage.aspx";
You can use default pages like, default.aspx or index.php etc...

Related

c# HTTP PATCH 400 error

I am currently working on implementing a class for accessing rest webservices with my C# program. I managed to do that for PUT, Post and GET, but I have problems with the Patch. The following error occurs everytime:
There is an exception error “System.Net.WebException” in System.ddll
Additional information: remote server reported: (400) Unvalid request
I have researched and tried out various things – to no avail. I would appreciate any help!
Many thanks in advance
public string WebserviceSenden()
{
// Create a request using a URL that can receive a post.
WebRequest request = WebRequest.Create( GrundURL + ErweiterungsURL);
// Set the Method property of the request to POST.
request.Method = Methode;
// Create POST data and convert it to a byte array.
string postData = DateSenden;
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// Set the ContentType property of the WebRequest.
request.ContentType = "application/json";
// Set the ContentLength property of the WebRequest.
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();
// Get the response.
WebResponse response = request.GetResponse();
// Display the status.
Console.WriteLine(((HttpWebResponse)response).StatusDescription);
// Get the stream containing content returned by the server.
dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
// Display the content.
Console.WriteLine(responseFromServer);
// Clean up the streams.
reader.Close();
dataStream.Close();
response.Close();
return responseFromServer;
}
public string WebserviceEmpfangen()
{
// Create a request for the URL.
WebRequest request = WebRequest.Create(
GrundURL + ErweiterungsURL);
// If required by the server, set the credentials.
request.Credentials = CredentialCache.DefaultCredentials;
// Get the response.
WebResponse response = request.GetResponse();
// Display the status.
Console.WriteLine(((HttpWebResponse)response).StatusDescription);
// Get the stream containing content returned by the server.
Stream dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
// Display the content.
Console.WriteLine(responseFromServer);
// Clean up the streams and the response.
reader.Close();
response.Close();
return responseFromServer;
}
}
private void button1_Click(object sender, EventArgs e)
{
String Jason = "";
RestClient AbfrageStarten = new RestClient();
AbfrageStarten.GrundURL = "URL";
AbfrageStarten.ErweiterungsURL = "540697";
Jason = AbfrageStarten.WebserviceEmpfangen();
var settings = new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore,
MissingMemberHandling = MissingMemberHandling.Ignore
};
var list = JsonConvert.DeserializeObject<List<Lagereinheit>>(Jason, settings);
KorrekturLagereinheit = list[0];
KorrekturLagereinheit.stueckzahl = 5858;
string Test;
Test = JsonConvert.SerializeObject(KorrekturLagereinheit, Formatting.None, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
RestClient AntwortSenden = new RestClient();
AntwortSenden.GrundURL = "URL";
AntwortSenden.ErweiterungsURL = "540697";
AntwortSenden.Methode = "Patch";
AntwortSenden.DateSenden = Test;
AntwortSenden.WebserviceSenden();
}
Error message
Many thanks in advance

Getting content from httpwebresponse exception

My remote server is throwing a web exception as bad request. But I know there is more information included in the error than what I get. If I look at the details from the exception it does not list the actual content of the response. I can see the content-type, content-length and content-encoding only. If I run this same message through another library (such as restsharp) I will see detailed exception information from the remote server. How can I get more details from the response since I know the remote server is sending them?
static string getXMLString(string xmlContent, string url)
{
//string Url;
string sResult;
//Url = ConfigurationManager.AppSettings["UserURl"] + url;
var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.ContentType = "application/xml";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
streamWriter.Write(xmlContent);
streamWriter.Flush();
streamWriter.Close();
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
sResult = result;
}
}
return sResult;
}
EDIT : Have you tried with a simple try-catch to see if you can get more details ?
try
{
var response = (HttpWebResponse)(request.GetResponse());
}
catch(Exception ex)
{
var response = (HttpWebResponse)ex.Response;
}
In my recherches in an answer for you, I noticed that in code there was something about encoding, that you didn't specified. Look here for exemple with such code.
var encoding = ASCIIEncoding.ASCII;
using (var reader = new System.IO.StreamReader(response.GetResponseStream(), encoding))
{
string responseText = reader.ReadToEnd();
}
Or here, in the doc, also.
// Creates an HttpWebRequest with the specified URL.
HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(url);
// Sends the HttpWebRequest and waits for the response.
HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
// Gets the stream associated with the response.
Stream receiveStream = myHttpWebResponse.GetResponseStream();
Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
// Pipes the stream to a higher level stream reader with the required encoding format.
StreamReader readStream = new StreamReader( receiveStream, encode );
Console.WriteLine("\r\nResponse stream received.");
Have you tried with such ?

C# - WebRequest.GetResponce(): The request was aborted: The connection was closed unexpectedly

i'm having a problem with this simple code which sends a request using provided url and reads html from responce. Looks like it's something with encoding of cyrillic symbols after ?q=, but i can't see why (url was actually obtained from browser address bar, not generated or anything else).
url =
"http://www.avito.ru/nizhniy_novgorod/kvartiry/sdam/na_dlitelnyy_srok?q=%D0%93%D0%B5%D0%BD%D0%B5%D1%80%D0%B0%D0%BB%D0%B0+%D0%98%D0%B2%D0%BB%D0%B8%D0%B5%D0%B2%D0%B0+10%D0%BA1";
string html = "";
try
{
Uri uri = new Uri(url);
WebRequest request = WebRequest.Create(uri);
request.Timeout = 100000;
using (WebResponse responce = request.GetResponse())
{
Stream stream = responce.GetResponseStream();
StreamReader reader = new StreamReader(stream);
html = reader.ReadToEnd();
}
}
catch (Exception e)
{
System.Console.WriteLine(e.Message);
}
Error occures in GetResponce() method. The message is:
The request was aborted: The connection was closed unexpectedly.
You should cast your request and response to HttpWebRequest and HttpWebResponse, respectively.
var url = "http://www.avito.ru/nizhniy_novgorod/kvartiry/sdam/na_dlitelnyy_srok?q=%D0%93%D0%B5%D0%BD%D0%B5%D1%80%D0%B0%D0%BB%D0%B0+%D0%98%D0%B2%D0%BB%D0%B8%D0%B5%D0%B2%D0%B0+10%D0%BA1";
string html = "";
try
{
Uri uri = new Uri(uri);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Timeout = 100000;
using (HttpWebResponse responce = (HttpWebResponse)request.GetResponse())
{
Stream stream = responce.GetResponseStream();
StreamReader reader = new StreamReader(stream);
html = reader.ReadToEnd();
Console.WriteLine(html);
}
}
catch (Exception e)
{
System.Console.WriteLine(e.Message);
}
Also, It seems that the url http://www.avito.ru/nizhniy_novgorod/kvartiry/sdam/na_dlitelnyy_srok?q=%D0%93%D0%B5%D0%BD%D0%B5%D1%80%D0%B0%D0%BB%D0%B0+%D0%98%D0%B2%D0%BB%D0%B8%D0%B5%D0%B2%D0%B0+10%D0%BA1 is invalid.
Using Fiddler, the url returns a 404 error.

why is my String throw error?

I want to target this string type "application/json" for urban airship api. Can you guys help me whats wrong with my string and structure?
string postData = "{"audience":"all","device_types":["android"],"notification":{"alert":"This is a broadcast."}}";
I did tried adding back slash "\" example below:
string postData = "{\"audience\":\"all\",\"device_types\":[\"android\"],\"notification\":{\"alert\":\"This is a broadcast.\"}}";
Below are my full code:
// Create a request using a URL that can receive a post.
WebRequest request = WebRequest.Create("https://go.urbanairship.com/api/push/");
// Set the Method property of the request to POST.
request.Method = "POST";
// Create POST data and convert it to a byte array.
string postData = "{'audience':'all','device_types':'['android']','notification': {'alert':'This is a broadcast.'}";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// Set the ContentType property of the WebRequest.
request.ContentType = "application/json";
// Set the ContentLength property of the WebRequest.
request.ContentLength = byteArray.Length;
//Do a http basic authentication somehow
string username = "Zx5EPSG7Qhu-BvYtz0laTg";
string password = "sIaj2CjASlm27pimHqOfhA";
string usernamePassword = username + ":" + password;
CredentialCache mycache = new CredentialCache();
mycache.Add(new Uri("https://go.urbanairship.com/api/push/"), "Basic", new NetworkCredential(username, password));
request.Credentials = mycache;
request.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(new ASCIIEncoding().GetBytes(usernamePassword)));
// 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();
// Get the response.
WebResponse response = request.GetResponse();
// Display the status.
Console.WriteLine(((HttpWebResponse)response).StatusDescription);
// Get the stream containing content returned by the server.
dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
// Display the content.
Console.WriteLine(responseFromServer);
// Clean up the streams.
reader.Close();
dataStream.Close();
response.Close();
I got below error:
400 Bad Request – The request body was invalid, either due to malformed JSON or a data validation error. See the response body for more detail.
This should work:
{
"audience" : "all",
"device_types" : ["android"],
"notification" : {
"alert" : "This is a broadcast."
}
}
You have small type in the first value, an additional ' sign after "all":
{
"audience": "all"',
"device_types": [
"android"
],
"notification": {
"alert": "This is a broadcast."
}
}
In future, you can use online validators for such cases, like JSONLint.

post data through httpwebrequest and get it in php

I have this php code in server :
foreach($_POST as $pdata)
echo " *-* ". $pdata." *-*<br> ";
and i am sending post data by httpwebrequest in c# :
HttpWebRequest httpWebRequest = HttpWebRequest.Create("http://127.0.0.1/22") as HttpWebRequest;
//Specifing the Method
httpWebRequest.Method = "POST";
//Data to Post to the Page, itis key value pairs; separated by "&"
string data = "Username=username&password=password";
//Setting the content type, it is required, otherwise it will not work.
httpWebRequest.ContentType = "application/x-www-form-urlencoded";
//Getting the request stream and writing the post data
using (StreamWriter sw = new StreamWriter(httpWebRequest.GetRequestStream()))
{
sw.Write(data);
}
//Getting the Respose and reading the result.
HttpWebResponse httpWebResponse = httpWebRequest.GetResponse() as HttpWebResponse;
using (StreamReader sr = new StreamReader(httpWebResponse.GetResponseStream()))
{
MessageBox.Show(sr.ReadToEnd());
}
static html codes of php page are shown.
but nothing of posted value are shown in messagebox .that means no data are posted.
what is wrong?
You need to get the bytes of the data.
Try this code, from this guy's blog post.
public string Post(string url, string data) {
string vystup = null;
try
{
//Our postvars
byte[] buffer = Encoding.ASCII.GetBytes(data);
//Initialisation, we use localhost, change if appliable
HttpWebRequest WebReq = (HttpWebRequest)WebRequest.Create(url);
//Our method is post, otherwise the buffer (postvars) would be useless
WebReq.Method = "POST";
//We use form contentType, for the postvars.
WebReq.ContentType = "application/x-www-form-urlencoded";
//The length of the buffer (postvars) is used as contentlength.
WebReq.ContentLength = buffer.Length;
//We open a stream for writing the postvars
Stream PostData = WebReq.GetRequestStream();
//Now we write, and afterwards, we close. Closing is always important!
PostData.Write(buffer, 0, buffer.Length);
PostData.Close();
//Get the response handle, we have no true response yet!
HttpWebResponse WebResp = (HttpWebResponse)WebReq.GetResponse();
//Let's show some information about the response
Console.WriteLine(WebResp.StatusCode);
Console.WriteLine(WebResp.Server);
//Now, we read the response (the string), and output it.
Stream Answer = WebResp.GetResponseStream();
StreamReader _Answer = new StreamReader(Answer);
vystup = _Answer.ReadToEnd();
//Congratulations, you just requested your first POST page, you
//can now start logging into most login forms, with your application
//Or other examples.
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return vystup.Trim()+"\n";
}

Categories