Google API Calendar OAUTH2 The remote server returned an error: (404) Not Found - api

async void GetEvent(string access_token) {
String serviceURL = "https://www.googleapis.com/calendar/v3/calendars/{email}/events";
String url = string.Format(serviceURL + "&key={0}&scope={1}", clientSecret, "https://www.googleapis.com/auth/calendar.events.readonly");
// sends the request
HttpWebRequest userinfoRequest = (HttpWebRequest)WebRequest.Create(url);
userinfoRequest.Method = "GET";
userinfoRequest.Headers.Add(string.Format("Authorization: Bearer {0}", access_token));
userinfoRequest.ContentType = "application/json";
userinfoRequest.Accept = "Accept=text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
userinfoRequest.UseDefaultCredentials = true;
userinfoRequest.Proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;
// gets the response
WebResponse userinfoResponse = await userinfoRequest.GetResponseAsync();
using (StreamReader userinfoResponseReader = new StreamReader(userinfoResponse.GetResponseStream())) {
// reads response body
string userinfoResponseText = await userinfoResponseReader.ReadToEndAsync();
output(userinfoResponseText);
}
}

Related

The server committed a protocol violation. Section=ResponseStatusLine : Issue

I created ASP.NET core 6 API project and used JWT authentication for each API end point.
But while executing in some physical system works fine but some other physical system and server throws below error
The server committed a protocol violation. Section=ResponseStatusLine
Sample Code
var request = (HttpWebRequest)WebRequest.Create(endpoint);
var token = System.Threading.Tasks.Task.Run(async() => await new Token("URL", "username", "pwd"])).Result;
request.Headers.Add("Authorization", "Bearer " + token);
request.Method = "POST";
var postData = JsonConvert.SerializeObject(Details, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
var data = Encoding.ASCII.GetBytes(postData);
request.ContentType = "application/json";
request.ContentLength = data.Length;
using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
var responses = (HttpWebResponse)request.GetResponse();
Sample code based on HTTP Client
using (var httpClient = new HttpClient())
{
using (var request = new HttpRequestMessage(new HttpMethod("POST"), endpoint))
{
string token = SalesOperationAPIToken("url", "usertest", "pwd");
request.Headers.TryAddWithoutValidation("accept", "*/*");
request.Headers.TryAddWithoutValidation("Authorization", "Bearer " + token);
string json = JsonConvert.SerializeObject(Details);
request.Content = new StringContent(json);
request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
var response = httpClient.SendAsync(request).Result;
var responseMessage = response.Content.ReadAsStringAsync().Result;
}
}
I am not sure what configuration need to be changed to get this worked in all system.
Thanks in advance.

Google API HTTP 401 - Token invalid - AuthSub token has wrong scope

I'm struggling with google api for a few days while sending a post request to Google sites API via C# application.
First I redeem the authorization code from google's servers by a GET request:
https://accounts.google.com/o/oauth2/auth?
scope=email%20profile&
state=security_token%3D138r5719ru3e1%26url%3Dhttps://oa2cb.mydomain/myHome&
redirect_uri=http://localhost&
response_type=code&
client_id= // CLIENT ID here...
access_type=online&
approval_prompt=auto
In the redirect uri I got the authorization code which I use to claim the
access token:
string RequestUrl;
RequestUrl = "https://www.googleapis.com/oauth2/v3/token";
WebRequest request = WebRequest.Create(RequestUrl);
request.Method = "POST";
// Create POST data and convert it to a byte array.
string postData = "code=4/aPJAhLvlGLxw1fjKDCOpEQjfoVtNDZYq7FzvrziUero#&" +
"client_id=//cilent id here&" +
"client_secret=client secret here&" +
"redirect_uri=http://localhost&" +
"grant_type=authorization_code";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteArray.Length;
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
WebResponse response = request.GetResponse();
Console.WriteLine(((HttpWebResponse)response).StatusDescription);
dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
Console.WriteLine(responseFromServer);
reader.Close();
dataStream.Close();
response.Close();
The response containing the token looks like that:
{
"access_token": "ya29.pAGX8f4e0ZyBazzq5rxWVS6lL1jRyj0_GCog5UEO3FiGT2h4cj10jee4ziAoA09vHRoVejN5p7Iw",
"token_type": "Bearer",
"expires_in": 3600,
"id_token": "eyJhbGciOiJSUzI1NiIsImtpZCI6IjE2NWQ2MzcwZTgzOTI5YmE4Y2E4ZWU5OTMzZTExZjg2Yzg4YzAwNjUifQ.eyJpc3MiOiJhY2NvdW50cy5nb29nbGUuY29tIiwic3ViIjoiMTA1OTc0NjQwMTUzNzU0NjU1MDE5IiwiYXpwIjoiOTkwMzUxMjA1MzY4LXBudGYxZXNtaXQ3a3Zlbmg5cnRvbW5pMmdhMmY0N2ZsLmFwcHMuZ29vZ2xldXNlcmNvbnRlbnQuY29tIiwiZW1haWwiOiJuaXIuazFAaGFpZmFuZXQub3JnLmlsIiwiYXRfaGFzaCI6Imc5MU5wOVRYS2JUaVEzcFpTM2Ewa1EiLCJlbWFpbF92ZXJpZmllZCI6dHJ1ZSwiYXVkIjoiOTkwMzUxMjA1MzY4LXBudGYxZXNtaXQ3a3Zlbmg5cnRvbW5pMmdhMmY0N2ZsLmFwcHMuZ29vZ2xldXNlcmNvbnRlbnQuY29tIiwiaGQiOiJoYWlmYW5ldC5vcmcuaWwiLCJpYXQiOjE0MzU4MjI2ODAsImV4cCI6MTQzNTgyNjI4MH0.CeaQ8S3GG-yeAwqjU1ixdB7ro2SVKp2QdVTXNWl6196oJeQU1LFLpZ9FtrpNEGSDKHXrO5zx0ldE52RYw8TwMKILUqqCHLOewVJQMjZ6tiPzt-b-qeUta6Op4Z9HerwkMK2sofl88G-XZ6jKc7gk1gGPVcATBU7x0-QPRhQxmDUzP7zceVeoOtBD8g7liVHakK9sA5RNonGt-N6SvzECqhSLss7kDuXc4dStnENhyv_9oTIpvVsQplE-cJz7fDHC7mkW7BfwsgKBE8XbruBz5-o3AG5RVGyUTYqDaoq9qr3_NqckiRISUS127scaYwcYPE22Q8L_2AnpfJU0vuxo6g"
}
And the final step is to call the google api using the access_token
this way:
HttpWebRequest req = (HttpWebRequest)System.Net.WebRequest.Create("https://sites.google.com/feeds/site/mydomain");
req.ContentType = "application/atom+xml";
req.Host = "sites.google.com";
req.Method = "POST";
req.Headers["Gdata-version"] = "1.4";
req.Headers["Authorization"] = "Bearer ya29.pAGX8f4e0ZyBazzq5rxWVS6lL1jRyj0_GCog5UEO3FiGT2h4cj10jee4ziAoA09vHRoVejN5p7Iw";
byte[] bytes = System.Text.Encoding.ASCII.GetBytes("<entry xmlns='http://www.w3.org/2005/Atom' xmlns:sites='http://schemas.google.com/sites/2008'><title>Source Site</title><summary>A new site to hold memories</summary><sites:theme>slate</sites:theme></entry>");
req.ContentLength = bytes.Length;
using (Stream os = req.GetRequestStream())
{
os.Write(bytes, 0, bytes.Length);
}
try
{
using (System.Net.WebResponse resp = req.GetResponse())
{
using (System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream()))
{
string i = sr.ReadToEnd().Trim();
}
}
}
catch (WebException ex)
{
using (var stream = ex.Response.GetResponseStream())
using (var reader = new StreamReader(stream))
{
Console.WriteLine(reader.ReadToEnd());
}
}
But at the end of this step I get a 401 http error.
Token invalid - AuthSub token has wrong scope
What am I doing wrong?
Thanks in advance
you are authenticating your users using the following scopes
scope=email%20profile&
The Sites Data API uses the following scope: https://sites.google.com/feeds/.

how to send api key to pushbullet api

i try to get the list of devices from pushpullet API
i'm using this code
string api = "my api key";
string url = "https://" + api + ":#api.pushbullet.com/v2/devices";
Uri uri = new Uri(url);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = "GET";
string result = string.Empty;
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (Stream responseStream = response.GetResponseStream())
{
using (StreamReader readStream = new StreamReader(responseStream, Encoding.UTF8))
{
result = readStream.ReadToEnd();
}
}
}
i get 401 "No valid API key provided."
when i try it on postman
it's work fine and i get the response.pushbullet api

Saving data in windows phone received from WCF/web service .

Saving data in windows phone received from WCF/web service .
The response may be received after sometime so how to handle this situation.
Saving data is no problem but How to handel if data is received late
You can use this code (show the code from my project):
public void sendPost(string postData, Action<MyResponse, Exception> callback, CreateResponse creater)
{
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(UrlRequest);
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.Accept = "application/json";
webRequest.AllowAutoRedirect = true;
webRequest.BeginGetRequestStream(new AsyncCallback(getRequestStreamCallback), new Request()
{
HttpRequest = webRequest,
PostData = postData,
Url = UrlRequest,
CallBack = callback,
Creater = creater
});
}
private void getRequestStreamCallback(IAsyncResult asynchronousResult)
{
var request = (Request)asynchronousResult.AsyncState;
// End the stream request operation
Stream postStream = request.HttpRequest.EndGetRequestStream(asynchronousResult);
byte[] byteArray = Encoding.UTF8.GetBytes(request.PostData);
// Add the post data to the web request
postStream.Write(byteArray, 0, byteArray.Length);
postStream.Close();
// Start the web request
request.HttpRequest.BeginGetResponse(new AsyncCallback(getResponseCallback), request);
}
private void getResponseCallback(IAsyncResult asynchronousResult)
{
var request = (Request)asynchronousResult.AsyncState;
try
{
HttpWebResponse response;
// End the get response operation
response = (HttpWebResponse)request.HttpRequest.EndGetResponse(asynchronousResult);
Stream streamResponse = response.GetResponseStream();
StreamReader streamReader = new StreamReader(streamResponse);
var myResponse = streamReader.ReadToEnd();
streamResponse.Close();
streamReader.Close();
response.Close();
MyResponse response_obj = request.Creater.CreateResponseObj();
using (MemoryStream stream = new MemoryStream(Encoding.Unicode.GetBytes(myResponse)))
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(response_obj.GetType());
response_obj = (GYResponse)serializer.ReadObject(stream);
if (request.CallBack != null)
{
request.CallBack.Invoke(response_obj, null);
}
}
}
catch (WebException e)
{
if (request.CallBack != null)
{
request.CallBack.Invoke(null, e);
}
}
}
public void getInfo(string uid, Action<MyResponse, Exception> callback)
{
CreateResponse creater = new CreateResponseGetInfo();
string model = "User";
string method = "getInfo";
Params parametrs = new Params();
parametrs.Uid = uid;
//create yor request
string request = getRequestString(model, method, parametrs, Atoken);
sendPost(request, callback, creater);
}
So, you call method, which send request to web service postRequester.getInfo(uid, ResponseHandler) and use delegate for processing result.
private void ResponseHandler(MyResponse result, Exception error)
{
if (error != null)
{
string err = error.Message;
return;
}
else
{
var infoResponse = result as ResponseGetInfo;
if (infoResponse != null)
{
//result processing..
}
}
}
All the web requests you make in a Windows Phone app are Asynchronous. That means, you make a web request from your app and attach a handler to handle the response when it comes. In the response handler, you will have to take care of the response and do whatever you want with it.
Check this link Using WebClient and HttpWebRequest

Google Clound Messaging server C#

I want to send message to GCM and I receive unavailable with status 200. What am I doing wrong?
var GoogleAppID = "";
var DeviceID = "";
var request = WebRequest.Create("https://android.googleapis.com/gcm/send");
request.Method = "POST";
request.Headers.Add("Authorization", "key=" + GoogleAppID);
request.ContentType = "application/json";
var message = new Message();
message.registration_ids.Add(DeviceID);
message.data.Add("gcm_message", "12345");
var jsonMessage = Newtonsoft.Json.JsonConvert.SerializeObject(message);
byte[] byteArray = Encoding.UTF8.GetBytes(jsonMessage);
request.ContentLength = byteArray.Length;
var reqStream = request.GetRequestStream();
reqStream.Write(byteArray, 0, byteArray.Length);
var response = request.GetResponse();
var responseCode = ((HttpWebResponse)response).StatusCode;
if (responseCode.Equals(HttpStatusCode.Unauthorized) || responseCode.Equals(HttpStatusCode.Forbidden))
{
return "Unauthorized - need new token";
}
else if (!responseCode.Equals(HttpStatusCode.OK))
{
return "Response from web service isn't OK";
}
var responseStream = response.GetResponseStream();
var streamReader = new StreamReader(responseStream);
var responseContent = streamReader.ReadToEnd();
streamReader.Close();
No need to build your own library, github already has one. Use the following.
https://github.com/Redth/GCMSharp