Getting a 401 error when submitting my datapayload to urbanairship - c#

I'm trying to send a test notification to my ipod via UrbanAirship with C#. I've tried many code snippets trying to send my notification to UrbanAirship from my Windows server, yet I always end up with a 401 error.
Here's my latest code:
string postData = "{\"aps\": {\"badge\": 1, \"alert\": \"Hello from Urban Airship!\"}, \"device_tokens\": [\""+ devToken +"\"]}";
var uri = new Uri("https://go.urbanairship.com/api/push/");
var encoding = new UTF8Encoding();
var request = (HttpWebRequest)WebRequest.Create(uri);
char[] charArray = Encoding.UTF8.GetChars(Encoding.UTF8.GetBytes(postData));
request.Method = "POST";
request.Credentials = new NetworkCredential(username, password);
request.ContentType = "application/json";
request.ContentLength = encoding.GetByteCount(charArray);
using (var stream = request.GetRequestStream())
{
stream.Write(encoding.GetBytes(postData), 0, encoding.GetByteCount(postData));
stream.Close();
var response = request.GetResponse();
response.Close();
}
Note: I've verified that my username and password are correct.
===UPDATE===
I would say that there's something woring with my urbanairship config or so but the following worked:
curl -X PUT -u "appKey:appSecret" -H "Content-Type: application/json" --data '{"alias": "myalias"}' https://go.urbanairship.com/api/device_tokens/myTOken/

Fixed, I've modified my code and most important: YOUR PASSWORD IS THE APPLICATION MASTER SECRET
string postData = "{\"aps\": {\"badge\": 1, \"alert\": \"Hello from Urban Airship!\"}, \"device_tokens\": [\""+ devToken +"\"]}";
var uri = new Uri("https://go.urbanairship.com/api/push/");
var encoding = new UTF8Encoding();
var request = (HttpWebRequest)WebRequest.Create(uri);
char[] charArray = Encoding.UTF8.GetChars(Encoding.UTF8.GetBytes(postData));
request.Method = "POST";
request.Credentials = new NetworkCredential(username, password);
request.ContentType = "application/json";
request.ContentLength = encoding.GetByteCount(charArray);
using (var stream = request.GetRequestStream())
{
stream.Write(encoding.GetBytes(postData), 0, encoding.GetByteCount(postData));
stream.Close();
var response = request.GetResponse();
response.Close();
}

Related

Convert CURL to C#

I have spent ages trying various different ways to convert this curl to c#. Could someone please help.
I am trying to do a http post and keep getting error 500.
here is what I want to convert:
curl --user username:password -X POST -d "browser=Win7x64-C1|Chrome32|1024x768&url=http://www.google.com" http://crossbrowsertesting.com/api/v3/livetests/
and this is what I have so far:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(baseurl);
request.Method = "POST";
request.Accept = "application/json";
request.Credentials = new NetworkCredential(username, password);
var response = request.GetResponse();
string text;
using (var sr = new StreamReader(response.GetResponseStream()))
{
text = sr.ReadToEnd();
values.Add(text);
}
Tried this method too but it didn't work:
List<string> data = new List<string>();
data.Add("browser=Win7x64-C1|Chrome20|1024x768");
data.Add("url=URL");
data.Add("format=json");
data.Add("callback=doit");
var request = WebRequest.Create("CrossBrowserTestingURL");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.Credentials = new NetworkCredential(username, password);
using (var writer = new StreamWriter(request.GetRequestStream()))
{
writer.Write("data=" + data);
}
var response = request.GetResponse();
string text;
using (var sr = new StreamReader(response.GetResponseStream()))
{
text = sr.ReadToEnd();
values.Add(text);
}
I modified the first one to write data to the request stream as per http://msdn.microsoft.com/en-us/library/debx8sh9(v=vs.110).aspx, does this work:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(baseurl);
request.Method = "POST";
request.Accept = "application/json";
request.Credentials = new NetworkCredential(username, password);
request.UserAgent = "curl/7.37.0";
request.ContentType = "application/x-www-form-urlencoded";
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
string data = "browser=Win7x64-C1|Chrome32|1024x768&url=http://www.google.com";
streamWriter.Write(data);
}
var response = request.GetResponse();
string text;
using (var sr = new StreamReader(response.GetResponseStream()))
{
text = sr.ReadToEnd();
values.Add(text);
}
Just implemented an experimental ASP.NET Core app that turns curl commands into C# code using Roslyn
Give it a try, please:
https://curl.olsh.me/
You can paste your command into curlconverter.com/csharp/ and it will convert it into this code using HttpClient:
using System.Net.Http.Headers;
HttpClient client = new HttpClient();
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "http://crossbrowsertesting.com/api/v3/livetests/");
request.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes("username:password")));
request.Content = new StringContent("browser=Win7x64-C1|Chrome32|1024x768&url=http://www.google.com");
request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
HttpResponseMessage response = await client.SendAsync(request);
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();

Add param POST request using HttpWebRequest async windows phone 8 - JSON [duplicate]

I need to call a method from a webservice, so I've written this code:
private string urlPath = "http://xxx.xxx.xxx/manager/";
string request = urlPath + "index.php/org/get_org_form";
WebRequest webRequest = WebRequest.Create(request);
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.
webRequest.ContentLength = 0;
WebResponse webResponse = webRequest.GetResponse();
But this method requires some parameters, as following:
Post data:
_username:'API USER', // api authentication username
_password:'API PASSWORD', // api authentication password
How can I add these parameters into this Webrequest?
Use stream to write content to webrequest
string data = "username=<value>&password=<value>"; //replace <value>
byte[] dataStream = Encoding.UTF8.GetBytes(data);
private string urlPath = "http://xxx.xxx.xxx/manager/";
string request = urlPath + "index.php/org/get_org_form";
WebRequest webRequest = WebRequest.Create(request);
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.ContentLength = dataStream.Length;
Stream newStream=webRequest.GetRequestStream();
// Send the data.
newStream.Write(dataStream,0,dataStream.Length);
newStream.Close();
WebResponse webResponse = webRequest.GetResponse();
If these are the parameters of url-string then you need to add them through '?' and '&' chars, for example http://example.com/index.aspx?username=Api_user&password=Api_password.
If these are the parameters of POST request, then you need to create POST data and write it to request stream. Here is sample method:
private static string doRequestWithBytesPostData(string requestUri, string method, byte[] postData,
CookieContainer cookieContainer,
string userAgent, string acceptHeaderString,
string referer,
string contentType, out string responseUri)
{
var result = "";
if (!string.IsNullOrEmpty(requestUri))
{
var request = WebRequest.Create(requestUri) as HttpWebRequest;
if (request != null)
{
request.KeepAlive = true;
var cachePolicy = new RequestCachePolicy(RequestCacheLevel.BypassCache);
request.CachePolicy = cachePolicy;
request.Expect = null;
if (!string.IsNullOrEmpty(method))
request.Method = method;
if (!string.IsNullOrEmpty(acceptHeaderString))
request.Accept = acceptHeaderString;
if (!string.IsNullOrEmpty(referer))
request.Referer = referer;
if (!string.IsNullOrEmpty(contentType))
request.ContentType = contentType;
if (!string.IsNullOrEmpty(userAgent))
request.UserAgent = userAgent;
if (cookieContainer != null)
request.CookieContainer = cookieContainer;
request.Timeout = Constants.RequestTimeOut;
if (request.Method == "POST")
{
if (postData != null)
{
request.ContentLength = postData.Length;
using (var dataStream = request.GetRequestStream())
{
dataStream.Write(postData, 0, postData.Length);
}
}
}
using (var httpWebResponse = request.GetResponse() as HttpWebResponse)
{
if (httpWebResponse != null)
{
responseUri = httpWebResponse.ResponseUri.AbsoluteUri;
cookieContainer.Add(httpWebResponse.Cookies);
using (var streamReader = new StreamReader(httpWebResponse.GetResponseStream()))
{
result = streamReader.ReadToEnd();
}
return result;
}
}
}
}
responseUri = null;
return null;
}
For doing FORM posts, the best way is to use WebClient.UploadValues() with a POST method.
Hope this works
webRequest.Credentials= new NetworkCredential("API_User","API_Password");
I have a feeling that the username and password that you are sending should be part of the Authorization Header. So the code below shows you how to create the Base64 string of the username and password. I also included an example of sending the POST data. In my case it was a phone_number parameter.
string credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes(_username + ":" + _password));
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(Request);
webRequest.Headers.Add("Authorization", string.Format("Basic {0}", credentials));
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.Method = WebRequestMethods.Http.Post;
webRequest.AllowAutoRedirect = true;
webRequest.Proxy = null;
string data = "phone_number=19735559042";
byte[] dataStream = Encoding.UTF8.GetBytes(data);
request.ContentLength = dataStream.Length;
Stream newStream = webRequest.GetRequestStream();
newStream.Write(dataStream, 0, dataStream.Length);
newStream.Close();
HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
Stream stream = response.GetResponseStream();
StreamReader streamreader = new StreamReader(stream);
string s = streamreader.ReadToEnd();
The code below differs from all other code because at the end it prints the response string in the console that the request returns. I learned in previous posts that the user doesn't get the response Stream and displays it.
//Visual Basic Implementation Request and Response String
Dim params = "key1=value1&key2=value2"
Dim byteArray = UTF8.GetBytes(params)
Dim url = "https://okay.com"
Dim client = WebRequest.Create(url)
client.Method = "POST"
client.ContentType = "application/x-www-form-urlencoded"
client.ContentLength = byteArray.Length
Dim stream = client.GetRequestStream()
//sending the data
stream.Write(byteArray, 0, byteArray.Length)
stream.Close()
//getting the full response in a stream
Dim response = client.GetResponse().GetResponseStream()
//reading the response
Dim result = New StreamReader(response)
//Writes response string to Console
Console.WriteLine(result.ReadToEnd())
Console.ReadKey()

How to upload a text/XML file to a web service

I have a web service URL which has username and password authentication mode. I have to first pass the username and password, and if I am authenticated, I can upload a text or XML file onto the server. I am looking for a C# code to do the same process, but I'm unable to find it.
Any suggestions would be highly appreciated.
I am using following code-
if (!string.IsNullOrEmpty(txtfile))
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
request.KeepAlive = false;
request.SendChunked = true;
request.AllowAutoRedirect = true;
request.Method = "Post";
request.ContentType = "text/xml";
request.Credentials = new NetworkCredential(userName, password);
var encoder = new UTF8Encoding();
var data = encoder.GetBytes(txtfile);
request.ContentLength = data.Length;
var reqStream = request.GetRequestStream();
reqStream.Write(data, 0, data.Length);
reqStream.Close();
WebResponse response = null;
response = request.GetResponse();
var reader = new StreamReader(response.GetResponseStream());
}
You might want to try using the WebClient Class. There is a simple example about the WebClient.UploadFile Method which could fit your scenario.

Wordnik authentication errors

I'm attempting to retrieve an authentication token from Wordnik by using the provided API. However, I cannot seem to get it to work; I seem to be stuck getting 401 and 403 errors.
The following is the code I am using to request authentication from the API:
string authRequest =
String.Format("http://api.wordnik.com//v4/account.json/authenticate/{0}",
this.userName);
HttpWebRequest request = WebRequest.Create(authRequest) as HttpWebRequest;
request.Method = WebRequestMethods.Http.Post;
request.ContentType = "application/x-www-form-urlencoded";
// When this is added, I get 403 errors
///request.Headers.Add("api_key", APIKey);
string postData = "password=" + password;
byte[] encodedData = UTF8Encoding.UTF8.GetBytes(postData);
request.ContentLength = encodedData.Length;
Stream stream = request.GetRequestStream();
stream.Write(encodedData, 0, encodedData.Length);
stream.Close();
string responseText;
using(HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
using(StreamReader reader = new StreamReader(response.GetResponseStream()))
{
responseText = reader.ReadToEnd();
Console.WriteLine(responseText);
Console.ReadLine();
}
}
Can any of you tell me what I'm doing incorrectly?
Any input is appreciated.
You have a double slash in the request URL:
"http://api.wordnik.com//v4"

How to add parameters into a WebRequest?

I need to call a method from a webservice, so I've written this code:
private string urlPath = "http://xxx.xxx.xxx/manager/";
string request = urlPath + "index.php/org/get_org_form";
WebRequest webRequest = WebRequest.Create(request);
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.
webRequest.ContentLength = 0;
WebResponse webResponse = webRequest.GetResponse();
But this method requires some parameters, as following:
Post data:
_username:'API USER', // api authentication username
_password:'API PASSWORD', // api authentication password
How can I add these parameters into this Webrequest?
Use stream to write content to webrequest
string data = "username=<value>&password=<value>"; //replace <value>
byte[] dataStream = Encoding.UTF8.GetBytes(data);
private string urlPath = "http://xxx.xxx.xxx/manager/";
string request = urlPath + "index.php/org/get_org_form";
WebRequest webRequest = WebRequest.Create(request);
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.ContentLength = dataStream.Length;
Stream newStream=webRequest.GetRequestStream();
// Send the data.
newStream.Write(dataStream,0,dataStream.Length);
newStream.Close();
WebResponse webResponse = webRequest.GetResponse();
If these are the parameters of url-string then you need to add them through '?' and '&' chars, for example http://example.com/index.aspx?username=Api_user&password=Api_password.
If these are the parameters of POST request, then you need to create POST data and write it to request stream. Here is sample method:
private static string doRequestWithBytesPostData(string requestUri, string method, byte[] postData,
CookieContainer cookieContainer,
string userAgent, string acceptHeaderString,
string referer,
string contentType, out string responseUri)
{
var result = "";
if (!string.IsNullOrEmpty(requestUri))
{
var request = WebRequest.Create(requestUri) as HttpWebRequest;
if (request != null)
{
request.KeepAlive = true;
var cachePolicy = new RequestCachePolicy(RequestCacheLevel.BypassCache);
request.CachePolicy = cachePolicy;
request.Expect = null;
if (!string.IsNullOrEmpty(method))
request.Method = method;
if (!string.IsNullOrEmpty(acceptHeaderString))
request.Accept = acceptHeaderString;
if (!string.IsNullOrEmpty(referer))
request.Referer = referer;
if (!string.IsNullOrEmpty(contentType))
request.ContentType = contentType;
if (!string.IsNullOrEmpty(userAgent))
request.UserAgent = userAgent;
if (cookieContainer != null)
request.CookieContainer = cookieContainer;
request.Timeout = Constants.RequestTimeOut;
if (request.Method == "POST")
{
if (postData != null)
{
request.ContentLength = postData.Length;
using (var dataStream = request.GetRequestStream())
{
dataStream.Write(postData, 0, postData.Length);
}
}
}
using (var httpWebResponse = request.GetResponse() as HttpWebResponse)
{
if (httpWebResponse != null)
{
responseUri = httpWebResponse.ResponseUri.AbsoluteUri;
cookieContainer.Add(httpWebResponse.Cookies);
using (var streamReader = new StreamReader(httpWebResponse.GetResponseStream()))
{
result = streamReader.ReadToEnd();
}
return result;
}
}
}
}
responseUri = null;
return null;
}
For doing FORM posts, the best way is to use WebClient.UploadValues() with a POST method.
Hope this works
webRequest.Credentials= new NetworkCredential("API_User","API_Password");
I have a feeling that the username and password that you are sending should be part of the Authorization Header. So the code below shows you how to create the Base64 string of the username and password. I also included an example of sending the POST data. In my case it was a phone_number parameter.
string credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes(_username + ":" + _password));
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(Request);
webRequest.Headers.Add("Authorization", string.Format("Basic {0}", credentials));
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.Method = WebRequestMethods.Http.Post;
webRequest.AllowAutoRedirect = true;
webRequest.Proxy = null;
string data = "phone_number=19735559042";
byte[] dataStream = Encoding.UTF8.GetBytes(data);
request.ContentLength = dataStream.Length;
Stream newStream = webRequest.GetRequestStream();
newStream.Write(dataStream, 0, dataStream.Length);
newStream.Close();
HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
Stream stream = response.GetResponseStream();
StreamReader streamreader = new StreamReader(stream);
string s = streamreader.ReadToEnd();
The code below differs from all other code because at the end it prints the response string in the console that the request returns. I learned in previous posts that the user doesn't get the response Stream and displays it.
//Visual Basic Implementation Request and Response String
Dim params = "key1=value1&key2=value2"
Dim byteArray = UTF8.GetBytes(params)
Dim url = "https://okay.com"
Dim client = WebRequest.Create(url)
client.Method = "POST"
client.ContentType = "application/x-www-form-urlencoded"
client.ContentLength = byteArray.Length
Dim stream = client.GetRequestStream()
//sending the data
stream.Write(byteArray, 0, byteArray.Length)
stream.Close()
//getting the full response in a stream
Dim response = client.GetResponse().GetResponseStream()
//reading the response
Dim result = New StreamReader(response)
//Writes response string to Console
Console.WriteLine(result.ReadToEnd())
Console.ReadKey()

Categories

Resources