I am trying to call an update api with the given parameter at the end of the url, however the update was unsuccessful and returns me an exception.
Here is my sample code for PUT method:
string result = "";
string json = "{" +
"\"ID\": " + 343336 + ", " +
"\"occurence\": " + 0 + ", " +
"\"user\": " + "Juan Dela Cruz" + ", " +
"\"comments\":" + "Test comments" +
"}";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://myurl/Update/343336");
request.Method = "PUT";
request.ContentType = "application/json";
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
HttpWebResponse httpResponse;
try
{
httpResponse = (HttpWebResponse)request.GetResponse();
}
catch (WebException ex)
{
httpResponse = (HttpWebResponse)ex.Response;
}
using (StreamReader reader = new StreamReader(httpResponse.GetResponseStream(), Encoding.UTF8))
{
result = reader.ReadToEnd();
}
}
console.WriteLine(result);
I already put a try catch on my code and it was returning me this error:
Unrecognized token: was expecting (true, false or null)
Any comments/suggestions TIA.
Related
I created a web request with post data then getting a response telling me if it contained something, and my question is on how to also capture something else from the response and write that in the console. Do I have to create a separate GET request? and how would i do that, and how do you get something from the get request and write that into the console.
https://imgur.com/JA0k1HJ
try
{
WebResponse webResponse = (HttpWebResponse)httpWebRequest.GetResponse();
Program.logincookie = cookieContainer;
StreamReader streamReader = new StreamReader(webResponse.GetResponseStream());
string text4 = streamReader.ReadToEnd();
streamReader.Close();
webResponse.Close();
if (!text4.Contains("Invalid username/password."))
{
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("[HIT] " + email + ":" + password);
File.AppendAllText("hits.txt", email + ":" + password + Environment.NewLine);
Valid++;
}
else
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("[BAD] " + email + ":" + password);
Invalid++;
}
}
catch (Exception)
{
Console.ForegroundColor = ConsoleColor.DarkRed;
Console.WriteLine("[BAD] " + email + ":" + password);
Invalid++;
}
I am fairly new to programming. I require exception handling for my HttpWebRequest to an Api. Below is my code, I haven't done error handling before so just an example of how to accomplish this will be appreciated.
private void button1_Click(object sender, EventArgs e)
{
Class1.PostDevices x = new Class1.PostDevices();
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(webAddr);
request.ContentType = "application/json";
request.Method = "POST";
request.Timeout = 5000;
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
string jsonstring;
MemoryStream stream1 = new MemoryStream();
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Class1.PostDevices));
x.notification = new Class1.Notification();
x.profile = "dev";
x.notification.message = "Hello World";
ser.WriteObject(stream1, x);
stream1.Position = 0;
StreamReader sr = new StreamReader(stream1);
jsonstring = sr.ReadToEnd();
Debug.WriteLine(JObject.Parse(jsonstring));
streamWriter.Write(jsonstring);
streamWriter.Flush();
}
HttpWebResponse httpResponse = (HttpWebResponse)request.GetResponse();
if (httpResponse.StatusCode == HttpStatusCode.OK)
{
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
string result = streamReader.ReadToEnd();
Debug.WriteLine(JObject.Parse(result));
Reponse.PostDevicesReponse MyResult = JsonConvert.DeserializeObject<Reponse.PostDevicesReponse>(result);
}
}
}
}
1) Create a folder named as "ExceptionTextFile" inside your application
2) Create a Separate Class like below to log the exception
using System;
using System.IO;
using context = System.Web.HttpContext;
//Define your application namespace here
namespace YourApplicationNamespace
{
public static class ExceptionLogging
{
private static String ErrorlineNo, Errormsg, extype, exurl, ErrorLocation;
public static void SendErrorToText(Exception ex)
{
var line = Environment.NewLine + Environment.NewLine;
ErrorlineNo = ex.StackTrace.ToString();
Errormsg = ex.Message;
extype = ex.GetType().ToString();
exurl = context.Current.Request.Url.ToString();
ErrorLocation = ex.Message.ToString();
try
{
//Create a folder named as "ExceptionTextFile" inside your application
//Text File Path
string filepath = context.Current.Server.MapPath("~/ExceptionTextFile/");
if (!Directory.Exists(filepath))
{
Directory.CreateDirectory(filepath);
}
//Text File Name
filepath = filepath + DateTime.Today.ToString("dd-MM-yy") + ".txt";
if (!File.Exists(filepath))
{
File.Create(filepath).Dispose();
}
using (StreamWriter sw = File.AppendText(filepath))
{
string error = "Log Written Date:" + " " + DateTime.Now.ToString()
+ line + "Error Line No :" + " " + ErrorlineNo + line
+ "Error Message:" + " " + Errormsg + line + "Exception Type:" + " "
+ extype + line + "Error Location :" + " " + ErrorLocation + line
+ " Error Page Url:" + " " + exurl + line + line;
sw.WriteLine("-----------Exception Details on " + " " + DateTime.Now.ToString() + "-----------------");
sw.WriteLine("-------------------------------------------------------------------------------------");
sw.WriteLine(line);
sw.WriteLine(error);
sw.WriteLine("--------------------------------*End*------------------------------------------");
sw.WriteLine(line);
sw.Flush();
sw.Close();
}
}
catch (Exception e)
{
e.ToString();
}
}
}
}
After that inside your button click event define try...catch block and log the exception like below
private void button1_Click(object sender, EventArgs e)
{
try
{
Class1.PostDevices x = new Class1.PostDevices();
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(webAddr);
request.ContentType = "application/json";
request.Method = "POST";
request.Timeout = 5000;
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
string jsonstring;
MemoryStream stream1 = new MemoryStream();
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Class1.PostDevices));
x.notification = new Class1.Notification();
x.profile = "dev";
x.notification.message = "Hello World";
ser.WriteObject(stream1, x);
stream1.Position = 0;
StreamReader sr = new StreamReader(stream1);
jsonstring = sr.ReadToEnd();
Debug.WriteLine(JObject.Parse(jsonstring));
streamWriter.Write(jsonstring);
streamWriter.Flush();
}
HttpWebResponse httpResponse = (HttpWebResponse)request.GetResponse();
if (httpResponse.StatusCode == HttpStatusCode.OK)
{
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
string result = streamReader.ReadToEnd();
Debug.WriteLine(JObject.Parse(result));
Reponse.PostDevicesReponse MyResult = JsonConvert.DeserializeObject<Reponse.PostDevicesReponse>(result);
}
}
}
}
catch (Exception e)
{
ExceptionLogging.SendErrorToText(e);
}
}
If any error appears go to the "ExceptionTextFile" folder and check the log. The exception would be logged there.
Try and revert me back if this solves your problem or not
I have following code which give "Error:MissingRegistration" response from GCM server.
public void SendPushNotification()
{
string stringregIds = null;
List<string> regIDs = _db.Directories.Where(i => i.GCM != null && i.GCM != "").Select(i => i.GCM).ToList();
//Here I add the registrationID that I used in Method #1 to regIDs
stringregIds = string.Join("\",\"", regIDs);
//To Join the values (if ever there are more than 1) with quotes and commas for the Json format below
try
{
string GoogleAppID = "AIzaSyA2Wkdnp__rBokCmyloMFfENchJQb59tX8";
var SENDER_ID = "925760665756";
var value = "Hello";
WebRequest tRequest;
tRequest = WebRequest.Create("https://android.googleapis.com/gcm/send");
tRequest.Method = "post";
Request.ContentType = "application/json";
tRequest.Headers.Add(string.Format("Authorization: key={0}", GoogleAppID));
tRequest.Headers.Add(string.Format("Sender: id={0}", SENDER_ID));
string postData = "{\"collapse_key\":\"score_update\",\"time_to_live\":108,\"delay_while_idle\":true,\"data\": { \"message\" : " + "\"" + value + "\",\"time\": " + "\"" + System.DateTime.Now.ToString() + "\"},\"registration_ids\":[\"" + stringregIds + "\"]}";
Byte[] byteArray = Encoding.UTF8.GetBytes(postData);
tRequest.ContentLength = byteArray.Length;
Stream dataStream = tRequest.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
WebResponse tResponse = tRequest.GetResponse();
dataStream = tResponse.GetResponseStream();
StreamReader tReader = new StreamReader(dataStream);
string sResponseFromServer = tReader.ReadToEnd();
TempData["msg1"] = "<script>alert('" + sResponseFromServer + "');</script>";
HttpWebResponse httpResponse = (HttpWebResponse)tResponse;
string statusCode = httpResponse.StatusCode.ToString();
tReader.Close();
dataStream.Close();
tResponse.Close();
}
catch (Exception ex)
{
}
}
But exact string returned by 'postData' posted by Postman or Fiddler gives positive response and notification arrived at device.
What I'm missing in my code please help me.
The postData returns this value which successfully posted by Postman And Fiddler
{"collapse_key":"score_update","time_to_live":108,"delay_while_idle":true,"data": { "message" : "Hello","time": "5/13/2016 5:50:59 PM"},"registration_ids":["cXMf6hkYIrw:APA91bGr-8y2Gy-qzNJ3zjrlf8t-4m9uDib9P0j8GW87bH5jq891-x_7P0qqItzlc_HXh11Arg76lCOcjXPrU9LAgtYLwllH2ySxA0ADSfiz3qPolajjvI3d3zE6Rh77dwRqXn3NnbAm"]}
The problem in your code is in ContentType
Instead of using this:-
Request.ContentType = "application/json";
Use
tRequest.ContentType = "application/json";
It will work
Try This:-
private string SendGCMNotification()
{
try
{
string message = "some test message";
//string tickerText = "example test GCM";
string contentTitle = "content title GCM";
string registration_id = "cXMf6hkYIrw:APA91bGr-8y2Gy-qzNJ3zjrlf8t-4m9uDib9P0j8GW87bH5jq891-x_7P0qqItzlc_HXh11Arg76lCOcjXPrU9LAgtYLwllH2ySxA0ADSfiz3qPolajjvI3d3zE6Rh77dwRqXn3NnbAm";
string postData =
"{ \"registration_ids\": [ \"" + registration_id + "\" ], " +
"\"data\": {\"contentTitle\":\"" + contentTitle + "\", " +
"\"message\": \"" + message + "\"}}";
string GoogleAppID = "AIzaSyA2Wkdnp__rBokCmyloMFfENchJQb59tX8";
WebRequest wRequest;
wRequest = WebRequest.Create("https://android.googleapis.com/gcm/send");
wRequest.Method = "POST";
wRequest.ContentType = " application/json;charset=UTF-8";
wRequest.Headers.Add(string.Format("Authorization: key={0}", GoogleAppID));
var bytes = Encoding.UTF8.GetBytes(postData);
wRequest.ContentLength = bytes.Length;
var stream = wRequest.GetRequestStream();
stream.Write(bytes, 0, bytes.Length);
stream.Close();
var wResponse = wRequest.GetResponse();
stream = wResponse.GetResponseStream();
var reader = new StreamReader(stream);
var response = reader.ReadToEnd();
var httpResponse = (HttpWebResponse)wResponse;
var status = httpResponse.StatusCode.ToString();
reader.Close();
stream.Close();
wResponse.Close();
//TODO check status
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return "sent";
}
I'm trying to get a http response from a web server which asks for my credentials in application/json. Although on their website they say I have to use POST Request, I get 405 HTTP status and a WebException as an answer. Here is my code:
private bool RunAuth(bool b, String user, String pass)
{
if(b)
{
HttpWebRequest h = (HttpWebRequest)WebRequest.Create("https://authserver.mojang.com/");
h.Method = "POST";
h.KeepAlive = false;
h.ContentType = "application/json";
String json = "{" + "\"agent\": {" + "\"name\": \"Minecraft\"," + "\"version\": 1" + "}," + "\"username\": \""+user+"\"," + "\"password\": \""+pass+"\"," + "\"clientToken\": \"" + tokenGenerated + "\"" + "}"; //tokenGenerated = Guid.NewGuid().ToString();
h.ContentLength = json.Length;
using(var stream = new StreamWriter(h.GetRequestStream()))
{
stream.Write(json);
stream.Flush();
stream.Close();
}
HttpWebResponse r = (HttpWebResponse)h.GetResponse();
using (var stream = new StreamReader(r.GetResponseStream()))
{
String result = stream.ReadToEnd();
File.WriteAllText(appdata + #"\.craftunio\authtest.txt", result);
}
return true;
}
else
{
return false;
}
}
You are calling the wrong endpoint. You should call
HttpWebRequest h = (HttpWebRequest)WebRequest.Create("https://authserver.mojang.com/authenticate");
My SOAP request works - hits the server and displays my request in the server logs and sends the response but I am unable to read the response with my codes (C# & ASP.NET) below.Am I missing something?
try
{
string url = "http://a.b.c.d/ABC/services/DOMFlightAvailability?wsdl";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.KeepAlive = false;
req.ProtocolVersion = HttpVersion.Version10;
req.Method = "POST";
string request = "<Request>"
+ "<Origin>BOM</Origin>"
+ "<Destination>BLR</Destination>"
+ "<DepartDate>2014-11-15</DepartDate>"
+ "<ReturnDate>2014-11-15</ReturnDate>"
+ "<AdultPax>1</AdultPax>"
+ "<ChildPax>1</ChildPax>"
+ "<InfantPax>1</InfantPax>"
+ "<Currency>INR</Currency>"
+ "<Clientid>123</Clientid>"
+ "<Clientpassword>123</Clientpassword>"
+ "<Clienttype>123</Clienttype>"
+ "<Preferredclass>E</Preferredclass>"
+ "<mode>ONE</mode>"
+ "<PreferredAirline>AI,G8,IC,6E,9W,S2,IT,9H,I7,SG</PreferredAirline>"
+ "</Request>";
byte[] postBytes = Encoding.ASCII.GetBytes("xmlRequest=" + request + "");
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = postBytes.Length;
Stream requestStream = req.GetRequestStream();
requestStream.Write(postBytes, 0, postBytes.Length);
requestStream.Close();
HttpWebResponse response = (HttpWebResponse)req.GetResponse();
Stream resStream = response.GetResponseStream();
var sr = new StreamReader(response.GetResponseStream());
string responseText = sr.ReadToEnd();
Response.Write(responseText);
lblResult.Text = responseText;
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
This is my other way of doing it - hits the server and trasmits the response but I am still unable to get the response data
try
{
DOMFlightAvailabilityPortTypeClient obj = new DOMFlightAvailabilityPortTypeClient();
string req = "<Request>"
+ "<Origin>BOM</Origin>"
+ "<Destination>DEL</Destination>"
+ "<DepartDate>2014-11-20</DepartDate>"
+ "<ReturnDate>2014-12-21</ReturnDate>"
+ "<AdultPax>1</AdultPax>"
+ "<ChildPax>0</ChildPax>"
+ "<InfantPax>0</InfantPax>"
+ "<Currency>INR</Currency>"
+ "<Clientid>123</Clientid>"
+ "<Clientpassword>123</Clientpassword>"
+ "<Clienttype>123</Clienttype>"
+ "<Preferredclass>E</Preferredclass>"
+ "<mode>ONE</mode>"
+ "<PreferredAirline>AI,G8,IC,6E,9W,S2,IT,9H,I7,SG</PreferredAirline>"
+ "</Request>";
string str = obj.getAvailability(req);
XmlDocument doc = new XmlDocument();
doc.LoadXml(str);
DataSet ds = new DataSet();
ds.ReadXml(new XmlTextReader(new StringReader(str)));
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}