Hello guys I am newbie and I am creating http get request to google calendar api, I just want to get event data with eventid and calendarid
https://developers.google.com/calendar/v3/reference/events/get
this is link of google api, where you can also test API
class Program
{
private static readonly HttpClient _Client = new HttpClient();
private static JavaScriptSerializer _Serializer = new JavaScriptSerializer();
static void Main(string[] args)
{
string CalendarID = "somecalendar#group.calendar.google.com";
string EventID = "someid";
{
string URL = "https://www.googleapis.com/calendar/v3/calendars/"+ CalendarID + "/events/"+ EventID;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
request.Method = "GET";
request.ContentType = "application/json";
var cust = new Dictionary<string, string>
{
{"somecalendar#group.calendar.google.com", "someid" }
};
var json = _Serializer.Serialize(cust);
string data = JsonConvert.SerializeObject(cust);
request.ContentLength = data.Length;
StreamWriter requestWriter = new StreamWriter(request.GetRequestStream(), Encoding.ASCII);
requestWriter.Write(data);
requestWriter.Close();
WebResponse webResponse = request.GetResponse();
Stream webStream = webResponse.GetResponseStream();
StreamReader responseReader = new StreamReader(webStream);
string response = responseReader.ReadToEnd();
responseReader.Close();
Console.WriteLine(response);
Console.ReadLine();
}
catch (Exception ex)
{
Console.WriteLine(ex);
Console.ReadLine();
}
}
in the end console writes this exception:
System.Net.ProtocolViolationException: Cannot send a content-body with
this verb-type.
can someone help?
Related
Working on Integrating Paytm with C# application.
I'm using Auto debit flow for integration purpose.
As part of this flow, SENDOTP API provided by Paytm needs to be invoked for sending the OTP to the customer mobile.
I have used the code which i got from the Paytm developer site.
https://developer.paytm.com/docs/send-otp-api/
.Net Code:
String url = "https://accounts-uat.paytm.com/signin/otp";
Dictionary<String, String> paytmParams = new Dictionary<String, String>();
paytmParams.Add("email", xxxxxxx#xxxxxxx.xxx);
paytmParams.Add("phone", xxxxxxxxxx);
paytmParams.Add("clientId", xxxxxxxx-xxx);
paytmParams.Add("scope", wallet);
paytmParams.Add("responseType", token);
try {
String postData = "JsonData="+ new JavaScriptSerializer().Serialize(paytmParams);
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.Headers.Add("ContentType", "application/json");
webRequest.Method = "POST";
using (StreamWriter streamWriter = new StreamWriter(webRequest.GetRequestStream())) {
streamWriter.Write(postData);
streamWriter.Flush();
streamWriter.Close();
}
string string responseData = string.Empty;
using (StreamReader responseReader = new StreamReader(webRequest.GetResponse())) {
responseData = responseReader.ReadToEnd();
}
} catch (Exception ex) {
Response.Write("Exception message: " + ex.Message.ToString());
}
Below is the request format :
JsonData = {
"email":"login2kkr#gmail.com",
"phone":"XXXXXXXXXX",
"clientId":"merchant-ABC",
"scope":"Wallet",
"responseType":"Token"
}
Response:
{
"status":"FAILURE",
"responseCode":"434",
"message":"Bad Request"
}
Regards,
Kishore.
I have tried using the below code and worked for me.
string url = "https://accounts.paytm.com/signin/otp";
Dictionary<string, string> paytmParams = new Dictionary<string, string>();
paytmParams.Add("email", "xxxxxxx#xxxxx.com");
paytmParams.Add("phone", "xxxxxxxxxxx");
paytmParams.Add("clientId", "paytm-web-secure");
paytmParams.Add("scope", "wallet");
paytmParams.Add("responseType", "token");
try
{
string postData = new JavaScriptSerializer().Serialize(paytmParams);
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.Headers.Add("ContentType", "application/json");
webRequest.Method = "POST";
using (StreamWriter streamWriter = new StreamWriter(webRequest.GetRequestStream()))
{
streamWriter.Write(postData);
streamWriter.Flush();
streamWriter.Close();
}
string responseData = string.Empty;
string statusCode = string.Empty;
string state = string.Empty;
using (StreamReader responseReader = new StreamReader(webRequest.GetResponse().GetResponseStream()))
{
responseData = responseReader.ReadToEnd();
}
}
catch (Exception ex)
{
Response.Write("Exception message: " + ex.Message.ToString());
}
I'm trying to log in into iCloud using a Json Post request in C#. Before trying to implement the code I was studying a little bit the iCloud requests using Chrome Console and using an Ad-on to replicate the requests in order to obtain the same result of the website.
First of All I checked the request directly from iCloud website:
And this is the response:
{
"serviceErrors" : [ {
"code" : "-20101",
"message" : "Il tuo IDĀ Apple o la password non sono corretti."
} ]
}
Using "Advance REST Client" ad Chrome plugin to replicate the request I ve tried the same Json request to the same Url. But I get Empty response:
I Also tried to copy and paste the whole Header (All the settings) and than send the request but the response is the same:
Anyone has an Advice?
UPDATE: I tried to implement A Json request through c# program:
var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://idmsa.apple.com/appleauth/auth/signin");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = "{accountName: \"briesanji #gmail.com\", password: \"testPassword\", rememberMe: false, trustTokens: []}";
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
The problem is that Execution breaks when the
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
is hit and it gives me this error: System.Net.WebException: 'Error Remote Server: (400) Request not valid.'
UPDATE: I solved in this way:
void POST(string url, string jsonContent)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
Byte[] byteArray = encoding.GetBytes(jsonContent);
request.ContentLength = byteArray.Length;
request.ContentType = #"application/json";
using (Stream dataStream = request.GetRequestStream())
{
dataStream.Write(byteArray, 0, byteArray.Length);
}
long length = 0;
try
{
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
length = response.ContentLength;
}
}
catch (WebException ex)
{
// Log exception and throw as for GET example above
}
}
string GET(string url)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
try
{
WebResponse response = request.GetResponse();
using (Stream responseStream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
return reader.ReadToEnd();
}
}
catch (WebException ex)
{
WebResponse errorResponse = ex.Response;
using (Stream responseStream = errorResponse.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8"));
String errorText = reader.ReadToEnd();
// log errorText
}
throw;
}
}
Anyways I tested also the Answer and it was good to.. So I check it as valid thanks.
With this i dont get any error and the response content of the second request just tells me that there were too many failed logins for the test account...
private static void ICloud()
{
var cc = new CookieContainer();
var first = (HttpWebRequest)WebRequest.Create("https://idmsa.apple.com/appleauth/auth/signin?widgetKey=83545bf919730e51dbfba24e7e8a78d2&locale=de_DE&font=sf");
first.Method = "GET";
first.CookieContainer = cc;
var response1 = (HttpWebResponse)first.GetResponse();
using (var streamReader = new StreamReader(response1.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
var second = (HttpWebRequest)WebRequest.Create("https://idmsa.apple.com/appleauth/auth/signin");
second.ContentType = "application/json";
second.Method = "POST";
second.Accept = "application/json";
second.CachePolicy = new RequestCachePolicy(RequestCacheLevel.NoCacheNoStore);
second.Referrer = "https://idmsa.apple.com/appleauth/auth/signin?widgetKey=83545bf919730e51dbfba24e7e8a78d2&locale=de_DE&font=sf";
second.Headers.Add("X-Requested-With", "XMLHttpRequest");
second.Headers.Add("X-Apple-Widget-Key", "83545bf919730e51dbfba24e7e8a78d2");
using (var streamWriter = new StreamWriter(second.GetRequestStream()))
{
string json = "{\"accountName\":\"test#icloud.com\",\"password\":\"test\",\"rememberMe\":false,\"trustTokens\":[]}";
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}
try
{
var response2 = (HttpWebResponse)second.GetResponse();
using (var streamReader = new StreamReader(response2.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
}
catch(WebException we)
{
using (var r = new StreamReader(we.Response.GetResponseStream()))
{
var result2 = r.ReadToEnd();
}
}
}
I want to consume rest api having post method in my project (web)/Windows service(C#).
Url : https://sampleurl.com/api1/token
I need to pass username and password for generating token.
I have written code like this.
string sURL = "https://sampleurl.com/api1/token/Actualusername/Actualpassword";
WebRequest wrGETURL;
wrGETURL = WebRequest.Create(sURL);
wrGETURL.Method = "POST";
wrGETURL.ContentType = #"application/json; charset=utf-8";
wrGETURL.ContentLength = 0;
HttpWebResponse webresponse = wrGETURL.GetResponse() as HttpWebResponse;
Encoding enc = System.Text.Encoding.GetEncoding("utf-8");
// read response stream from response object
StreamReader loResponseStream = new StreamReader(webresponse.GetResponseStream(), enc);
// read string from stream data
string strResult = loResponseStream.ReadToEnd();
// close the stream object
loResponseStream.Close();
// close the response object
webresponse.Close();
Response.Write(strResult);
I am getting error: No connection could be made because the target machine actively refused it
Is it right way to consume rest api in C#?
This all very much depend on the API's documentation, but to write data to the request body, get the request stream and then write the string to the stream.
again, this depends on what the API you are authenticating with and without knowing which one is guesswork on my part.
string sURL = "https://sampleurl.com/api1/token";
WebRequest wrGETURL;
wrGETURL = WebRequest.Create(sURL);
wrGETURL.Method = "POST";
wrGETURL.ContentType = #"application/json; charset=utf-8";
using (var stream = new StreamWriter(wrGETURL.GetRequestStream()))
{
var bodyContent = new
{
username = "Actualusername",
password = "Actualpassword"
}; // This will need to be changed to an actual class after finding what the specification sheet requires.
var json = JsonConvert.SerializeObject(bodyContent);
stream.Write(json);
}
HttpWebResponse webresponse = wrGETURL.GetResponse() as HttpWebResponse;
Encoding enc = System.Text.Encoding.GetEncoding("utf-8");
// read response stream from response object
StreamReader loResponseStream = new StreamReader(webresponse.GetResponseStream(), enc);
// read string from stream data
string strResult = loResponseStream.ReadToEnd();
// close the stream object
loResponseStream.Close();
// close the response object
webresponse.Close();
Response.Write(strResult);
Consume API with Basic Authentication in C#
class Program
{
static void Main(string[] args)
{
BaseClient clientbase = new BaseClient("https://website.com/api/v2/", "username", "password");
BaseResponse response = new BaseResponse();
BaseResponse response = clientbase.GetCallV2Async("Candidate").Result;
}
public async Task<BaseResponse> GetCallAsync(string endpoint)
{
try
{
HttpResponseMessage response = await client.GetAsync(endpoint + "/").ConfigureAwait(false);
if (response.IsSuccessStatusCode)
{
baseresponse.ResponseMessage = await response.Content.ReadAsStringAsync();
baseresponse.StatusCode = (int)response.StatusCode;
}
else
{
baseresponse.ResponseMessage = await response.Content.ReadAsStringAsync();
baseresponse.StatusCode = (int)response.StatusCode;
}
return baseresponse;
}
catch (Exception ex)
{
baseresponse.StatusCode = 0;
baseresponse.ResponseMessage = (ex.Message ?? ex.InnerException.ToString());
}
return baseresponse;
}
}
public class BaseResponse
{
public int StatusCode { get; set; }
public string ResponseMessage { get; set; }
}
public class BaseClient
{
readonly HttpClient client;
readonly BaseResponse baseresponse;
public BaseClient(string baseAddress, string username, string password)
{
HttpClientHandler handler = new HttpClientHandler()
{
Proxy = new WebProxy("http://127.0.0.1:8888"),
UseProxy = false,
};
client = new HttpClient(handler);
client.BaseAddress = new Uri(baseAddress);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var byteArray = Encoding.ASCII.GetBytes(username + ":" + password);
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
baseresponse = new BaseResponse();
}
}
I'm trying to get a response from SOAP webservice, but I'm falling into a webexception Error 500.
This my class to get a response:
public static string getResponse()
{
StringBuilder xml = new StringBuilder();
//xml.Append(#"<?xml version=""1.0"" encoding=""utf-8""?>");
xml.Append(#"<soapenv:Envelope xmlns:soapenv=""http://schemas.xmlsoap.org/soap/envelope/"" xmlns:br=""http://www.totvs.com.br/br/"" >").Replace(#"\", "");
xml.Append("<soap:Envelope/>");
xml.Append("<soapenv:Body>");
xml.Append("<br:RealizarConsultaSQLAuth>");
xml.Append("<br:codSentenca>GLOBAL_054</br:codSentenca>");
xml.Append("<br:codColigada>0</br:codColigada>");
xml.Append("<br:codAplicacao>V</br:codAplicacao>");
xml.Append("<br:Usuario>xxxx</br:Usuario>");
xml.Append("<br:Senha>xxxx</br:Senha>");
xml.Append("<br:parameters>codcoligada=1;codsistema=V;codusuario=mestre</br:parameters>");
xml.Append("</br:RealizarConsultaSQLAuth>");
xml.Append("</soapenv:Body>");
xml.Append("</soapenv:Envelope>");
string s = getUKMailData(xml.ToString(), "http://xxx.xxxx.com.br:99/xxxx/wsConsultaSQL.asmx");
return s;
}
public static string getUKMailData(string xml, string address)
{
string result = "";
HttpWebRequest request = CreateWebRequest(address);
XmlDocument soapEnvelopeXml = new XmlDocument();
string teste = xml.Replace(#"\", "");
soapEnvelopeXml.LoadXml(teste);
try
{
using (Stream stream = request.GetRequestStream())
{
soapEnvelopeXml.Save(stream);
}
using (WebResponse response = request.GetResponse())
{
using (StreamReader rd = new StreamReader(response.GetResponseStream()))
{
string soapResult = rd.ReadToEnd();
result = soapResult;
}
}
}
catch (WebException wex)
{
var pageContent = new StreamReader(wex.Response.GetResponseStream()).ReadToEnd();
}
return result;
}
public static HttpWebRequest CreateWebRequest(string url)
{
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.Headers.Add("SOAP:Action");
webRequest.Headers.Add("username", "xxx");
webRequest.Headers.Add("password", "xxx");
// webRequest.ContentType = "text/xml;charset=\"utf-8\"";
webRequest.Accept = "text/xml";
webRequest.Method = "POST";
webRequest.PreAuthenticate = true;
webRequest.Credentials = CredentialCache.DefaultCredentials;
return webRequest;
}
anyone can help me? I already read a series of articles that unfortunately did not help me. Thanks a lot!
Your request maybe true but server-side doesn't know how to process your data. Maybe parameters which are sent fault. Please check your server-side so end-point.
im making an app in wpf, which uses a restful api, from sharefile im making the autorisation
so far i have this
private void Button_Click_1(object sender, RoutedEventArgs e)
{
Uri uri = new Uri("https://secure.sharefile.com/oauth/authorize");
HttpWebRequest request = WebRequest.CreateHttp(uri);
shareFileWebView.Navigate(uri);
request.Method = "POST";
shareFileWebView. // but i supose to get something from here
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Console.WriteLine(response.StatusCode);
JObject token = null;
using (var reader = new StreamReader(response.GetResponseStream()))
{
string body = reader.ReadToEnd();
token = JObject.Parse(body);
}
OAuth2Token _tokene =new OAuth2Token(token);
}
i need to get that token but how can i get from the webbrowser? in the webr browser the user fills his accounts data, any ideas??
Does this link give you what you need?
http://api.sharefile.com/rest/api-key.aspx
Http request with body ( for example send image ) :
public string httpRequest(string url,byte[] image)
{
try
{
var request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "Post";
request.ContentType = "multipart/form-data";
request.ContentLength = image.Length;
using (Stream postStream = request.GetRequestStream())
{
postStream.Write(image, 0, image.Length);
postStream.Close();
WebResponse response = request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
if (!string.IsNullOrEmpty(responseString))
return responseString;
return null;
}
}
catch (Exception ex)
{
return ex.Message;
}
}
or :
public string RunCommand()
{
ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;
var request = (HttpWebRequest)WebRequest.Create("url");
var response = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
response.Close();
return responseString;
}