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.
Related
How to post the following data to servlet url:
Data:
enc_request=63957FB55DD6E7B968A7588763E08B240878046EF2F520C44BBC63FB9CCE726209A4734877F5904445591304ABB2F5E598B951E39EAFB9A24584B00590ADB077ADE5E8C444EAC5A250B1EA96F68D22E44EA2515401C2CD753DBA91BD0E7DFE7341BE1E7B7550&access_code=8JXENNSSBEZCU8KQ&command=confirmOrder&request_type=XML&response_type=XML&version=1.1
Url:
"https://logintest.ccavenue.com/apis/servlet/DoWebTrans";
I tried https://social.msdn.microsoft.com/Forums/vstudio/en-US/df76fbfa-2931-4c9f-8671-785307243f62/post-request-to-a-java-servlet-and-process-httpresponse-using-net?forum=wcf . But I'm getting the error: C# System.Net.WebException: The underlying connection was closed: An unexpected error occurred on a send
Below is my code:
StringBuilder sbQueryString = new StringBuilder();
CCACrypto ccaCrypto = new CCACrypto();
string workingKey = "14A246E9D4341159638AC8EB776F3BE6";
//put in the 32bit alpha numeric key in the quotes provided here
sbQueryString.Append("enc_request=");
sbQueryString.Append(ccaCrypto.Encrypt(GenerateOrderXml(appointmentId), workingKey));
sbQueryString.Append("&");
sbQueryString.Append("access_code=");
sbQueryString.Append("AVQJ68DL46BW00JQWB");
sbQueryString.Append("&");
sbQueryString.Append("Command=");
sbQueryString.Append("cancelOrder");
sbQueryString.Append("&");
sbQueryString.Append("request_type=XML&response_type=XML");
sbQueryString.Append("&");
sbQueryString.Append("version=1.1");
//Response.Redirect("../ccAvenue/ccavAPIHandler.aspx?" + sbQueryString.ToString(), false);
//string url = "https://logintest.ccavenue.com/apis/servlet/DoWebTrans";
string url = "https://180.179.175.17/apis/servlet/DoWebTrans";
// Create a request using a URL that can receive a post.
WebRequest request = WebRequest.Create(url);
// Set the Method property of the request to POST.
request.Method = "POST";
// Create POST data and convert it to a byte array.
string postData = sbQueryString.ToString();
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// Set the ContentType property of the WebRequest.
request.ContentType = "application/x-www-form-urlencoded";
// 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();
You can try simplifying your code by using a WebClient:
using (var client = new WebClient())
{
var data = new NameValueCollection
{
{ "enc_request", "63957FB55DD6E7B968A7588763E08B240878046EF2F520C44BBC63FB9CCE726209A4734877F5904445591304ABB2F5E598B951E39EAFB9A24584B00590ADB077ADE5E8C444EAC5A250B1EA96F68D22E44EA2515401C2CD753DBA91BD0E7DFE7341BE1E7B7550" },
{ "access_code", "8JXENNSSBEZCU8KQ" },
{ "command", "confirmOrder" },
{ "request_type", "XML" },
{ "response_type", "XML" },
{ "version", "1.1" },
};
var url = "https://logintest.ccavenue.com/apis/servlet/DoWebTrans";
byte[] result = client.UploadValues(url, data);
}
I have utilities that post standard XML, but am faced with interacting with a server that requires something I'm not familiar with.
The expected XML format is like this:
"xmldata=<txn><element_1>element_1_value</element_1><element_2>element_2_value</element_2></txn>"
When I post using my standard method:
byte[] data = Encoding.ASCII.GetBytes(XDocumentToString(xml));
var client = new WebClient();
client.Headers.Add("Content-Type", "text/xml");
byte[] result = client.UploadData(new Uri(url), "POST", data);
string resultString = Encoding.ASCII.GetString(result);
return XDocument.Parse(resultString);
I get an error message about the XML not being formatted correctly.
When I use some stuff I've found:
var request = _requestFactory.CreateCreditCardSaleRequest(xmlStringFromAbove);
WebRequest webRequest = WebRequest.Create("https://domain.com/process_some_xml.do");
webRequest.Method = "POST";
byte[] byteArray = Encoding.UTF8.GetBytes(request);
// Set the ContentType property of the WebRequest.
webRequest.ContentType = "text/xml; encoding='utf-8'";
// Set the ContentLength property of the WebRequest.
webRequest.ContentLength = byteArray.Length;
// Get the request stream.
Stream dataStream = webRequest.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 = webRequest.GetResponse();
// Display the status.
var httpWebResponse = (HttpWebResponse) response;
Console.WriteLine(httpWebResponse.StatusDescription);
// Get the stream containing content returned by the server.
dataStream = response.GetResponseStream();
the response seems to indicate success, but no response content as expected.
I suspect it has something to do with the "xmldata=" at the beginning of the request, but cannot be sure.
Any suggestions?
Judging from the xmldata=, it sounds like the API wants the data sent as form-urlencoded. I suggest trying this:
string dataStr = "xmldata=" + HttpUtility.UrlEncode(XDocumentToString(xml));
byte[] data = Encoding.ASCII.GetBytes(dataStr);
and this:
client.Headers.Add("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
I am currently having a problem.
I am trying to post my data to a PHP document but it does not get the whole value.
Somewhere in the middle it stops posting.
Does anyone know where the problem is located?
The bytearray is 7401 long. That cant be to long rigth?
My code is below:
public string RecieveData(string url, string postData = "")
{
WebRequest request = WebRequest.Create(url);
// If required by the server, set the credentials.
NetworkCredential nc = new NetworkCredential("user", "pass");
Stream dataStream;
if (postData != "")
{
// Set the Method property of the request to POST.
request.Method = "POST";
// Create POST data and convert it to a byte array.string postData = "This is a test that posts this string to a Web server.";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// Set the ContentType property of the WebRequest.
request.ContentType = "application/x-www-form-urlencoded";
// Set the ContentLength property of the WebRequest.
request.ContentLength = byteArray.Length;
// Get the request stream.
dataStream = request.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close();
}
request.Credentials = nc;
// Get the response.
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
// Display the status.
Console.WriteLine(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);
// Cleanup the streams and the response.
reader.Close();
dataStream.Close();
response.Close();
return responseFromServer;
/*
}
catch (Exception)
{
MessageBox.Show("Er is iets fout gegaan met verbinden");
return "";
}
*/
}
7401 is not too long.
My guess is that the data you are posting are not fully URL-encoded, e.g. one of the characters in the byte array causes the PhP parser to stop. Make sure you are looking at the raw data (e.g. using Wireshark).
I trying to use Google GCM for sending push notifications. But get a WebException that says that the remote server returns 401 unautorized. I can't foung why it doen't work.
Anyone that knows why it doesn't work?
Here is my code:
ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback(ValidateServerCertificate);
HttpWebRequest Request = (HttpWebRequest)WebRequest.Create("https://android.googleapis.com/gcm/send");
Request.Method = "POST";
Request.KeepAlive = false;
string postData = "{ 'registration_ids': [ '"+registrationId+"' ], 'data': {'message': '"+message+"'}}";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
Request.ContentType = "application/json";
//Request.ContentLength = byteArray.Length;
//Request.Headers.Add(HttpRequestHeader.Authorization, "GoogleLogin auth=" + AuthString);
Request.Headers.Add(HttpRequestHeader.Authorization, "Authorization: key=AIzaSyCEygavdzrNM3pWNPtvaJXpvW66CKnjH_Y");
//-- Delegate Modeling to Validate Server Certificate --//
//-- Create Stream to Write Byte Array --//
Stream dataStream = Request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
//-- Post a Message --//
WebResponse Response = Request.GetResponse();
HttpStatusCode ResponseCode = ((HttpWebResponse)Response).StatusCode;
if (ResponseCode.Equals(HttpStatusCode.Unauthorized) || ResponseCode.Equals(HttpStatusCode.Forbidden))
{
var text = "Unauthorized - need new token";
}
else if (!ResponseCode.Equals(HttpStatusCode.OK))
{
var text = "Response from web service isn't OK";
}
StreamReader Reader = new StreamReader(Response.GetResponseStream());
string responseLine = Reader.ReadLine();
Reader.Close();
Daniel - Dude there is an issue with the GCM documentation ! Use Browser key as the authorization key at the place of Server API key . It will work.
OK, i am just shooting in the dark here. Take a look at this line:
Request.Headers.Add(HttpRequestHeader.Authorization, "Authorization: key=AIzaSyCEygavdzrNM3pWNPtvaJXpvW66CKnjH_Y");
Shouldn't it be:
Request.Headers.Add(HttpRequestHeader.Authorization, "key=AIzaSyCEygavdzrNM3pWNPtvaJXpvW66CKnjH_Y");
Since you're telling it this is a Authorization header, there's no need to add 'Authorization: ' again, does it?
Also, make sure the string constant 'HttpRequestHeader.Authorization' is 'Authorization'.
So i'm making a program where you input some information. One part of the information requires alot of text, we are talking 100+ characters. What I found is when the data is to large it won't send the data at all. Here is the code I am using:
public void HttpPost(string URI, string Parameters)
{
// this is what we are sending
string post_data = Parameters;
// this is where we will send it
string uri = URI;
// create a request
HttpWebRequest request = (HttpWebRequest) WebRequest.Create(uri);
request.KeepAlive = false;
request.ProtocolVersion = HttpVersion.Version10;
request.Method = "POST";
// turn our request string into a byte stream
byte[] postBytes = Encoding.ASCII.GetBytes(post_data);
// this is important - make sure you specify type this way
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = postBytes.Length;
Stream requestStream = request.GetRequestStream();
// now send it
requestStream.Write(postBytes, 0, postBytes.Length);
requestStream.Close();
}
I am then calling that method like so:
HttpPost(url, "data=" + accum + "&pass=HRS");
'accum' is the large amount of data that I am sending. This method works if I send a small amount of data. But then when it's large it won't send. Is there any way to send a post request to a .php page on my website that can exceed 100+ characters?
Thanks.
You're only calling GetRequestStream. That won't make the request - by default it will be buffered in memory, IIRC.
You need to call WebRequest.GetResponse() to actually make the request to the web server.
So change the end of your code to:
// Using statement to auto-close, even if there's an exception
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(postBytes, 0, postBytes.Length);
}
// Now we're ready to send the data, and ask for a response
using (WebResponse response = request.GetResponse())
{
// Do you really not want to do anything with the response?
}
I'm using this way to post JSON data inside the request , I guess it's a little bit different but it may work ,
httpWebRequest = (HttpWebRequest)WebRequest.Create(RequestURL);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Accept = "application/json";
httpWebRequest.Method = "POST";
String username = "UserName";
String password = "passw0rd";
String encoded = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(username + ":" + password));
httpWebRequest.Headers.Add("Authorization", "Basic " + encoded);
using (StreamWriter sw = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = "{" +
"\"user\":[ \"" + user + "\"] " +
"}";
sw.Write(json);
sw.Flush();
sw.Close();
}
using (HttpWebResponse httpResponse = (HttpWebResponse)httpWebRequest.GetResponse())
{
//var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var responseText = streamReader.ReadToEnd();
//Now you have your response.
//or false depending on information in the response
}
httpResponse.Close();
}