The question: How to use people.get with the "me" parameter?
I know how to get the json object when using https://www.googleapis.com/plus/v1/people/{id}?key={key}
but what parameters should I include when Im using "me" as id?
(I use response_type=code in the auth)
Edit: (fixed)
I am using ASP.NET, and I found this link, but the POST request for the access token json throws an error. Sending the request works but, but when I use GetResponse(), I get error(400). And also Im not sure if the uri that I use is correct: https://accounts.google.com/o/oauth2/token
Edit 2:
Problem solved. The request was bad because I used UTF32Encoding instead of UTF8Encoding when converting the parameter string to byte[] before writing to Stream. With UTF8Encoding works good. :)
Code that I wrote after this question:
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(uri);
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.Method = "POST";
UTF8Encoding utfenc = new UTF8Encoding();
byte[] bytes = utfenc.GetBytes(parameters);
Stream os = null;
try // send the post
{
webRequest.ContentLength = bytes.Length; // Count bytes to send
os = webRequest.GetRequestStream();
os.Write(bytes, 0, bytes.Length); // Send it
}
// error handling...
try // get the response
{
HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
if (webResponse == null)
{ return null; }
StreamReader sr = new StreamReader(webResponse.GetResponseStream());
return sr.ReadToEnd().Trim();
}
// error handling...
he called this with the parameters from here, and the returned string(json) contains my access_token.
We have developed a .NET client library for Google+ APIs. This library makes it very easy to use Google+ APIs from any .NET programming languages like C#, VB.NET or ASP.NET
You can find more details about the .NET library for Google+ here: http://www.googleplustips.com/resources/3332-NET-Library-Google-APIs-released.aspx
The current version supports all Google+ APIs version 1, and works with API Key. Calling any Google APIs require only a single method call.
You can use me ID as long as you access the app with the access token of an (OAuth) authenticated user. To quote from the G+ API documentation:
If using the userId value "me", this method requires authentication using a token that has been granted the OAuth scope https://www.googleapis.com/auth/plus.me. Read more about using OAuth.
Example: when using the PHP API client, before issuing e.g.
$plus_api = new apiPlusService($client); // $client is the apiClient() object
$plus_api->activities->listActivities('me', ...);
you have to set the access token of the authenticated user first by executing:
$client->setAccessToken($access_token);
With that set, the me ID will be recognized without a problem.
I sent a POST request (info here) to get the Oauth2 access_token and used:
https://www.googleapis.com/plus/v1/people/me?key={key}&access_token={token}
GetActivity and ListComments are getting all the data, or it has some method(using nextPageToken) to get all the items?
Each method call returns the resultset page by page. The returned object has a property called NextPageToken which can be passed with the next call to retrieve the next page of the result set.
Related
I am able generate access token with docusign site by using link https://developers.docusign.com/oauth-token-generator
But when try to get access token in our system using c# code then getting message (The remote server returned an error: (400) Bad Request.)
I follow the authenticate process mentioned in below link.
https://developers.docusign.com/esign-rest-api/guides/authentication/oauth2-code-grant
I able to get authentication code. I used this authentication code to hit API (https://account-d.docusign.com/oauth/token).
Below is my code sample
string integrationKey = "key removed";
string secretKey = "key removed";
var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://account-d.docusign.com/oauth/token");
httpWebRequest.ContentType = "application/x-www-form-urlencoded";
httpWebRequest.Method = "POST";
string apiStoreConsumer = "removed";
httpWebRequest.Headers.Add("Authorization", "Basic " + apiStoreConsumer);
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string input = "authorization_code&authorization_code= <authentication code goes here>;
streamWriter.Write(input);
streamWriter.Flush();
streamWriter.Close();
}
WebResponse response = (HttpWebResponse)httpWebRequest.GetResponse();
Query:
Why am I getting 400 error?
Do we have any expiry time for access token, if yes then how long?
Does authentication code get change for every request?
Please help me on this.
Thank You!
I recommend you use a library for OAuth in .NET/C#.
If you want to see how this is done, please clone this repo.
The issue is that you need to first get a code and then exchange it for a token. There are 2 steps involved if you do this manually.
The first step requires you to authenticate the user in a browser before you can call any API.
During that step you need to pass in your integration key and redirect back to your URL.
Once redirected back you'll receive a code that can be exchanged for an access token using the API call you had talks about.
How can I call HTTP GET using JSON parameters in content body?
I tried this:
HttpWebRequest.WebRequest.Create(_uri);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "GET";
httpWebRequest.Headers.Add("X-AUTH-TOKEN", _apiKey);
using(var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream())) {
string _json = "\"{\"filter\": {\"relation\": \"equals\", \"attribute\": \"state\", \"value\": \"CA\" }, \"insights\": {\"field\": \"family.behaviors\", \"calculations\": [\"fill_count\"]}}";
streamWriter.Write(_json);
streamWriter.Flush();
streamWriter.Close();
}
var httpResponse = (HttpWebResponse) httpWebRequest.GetResponse();
using(var streamReader = new StreamReader(httpResponse.GetResponseStream())) {
var result = streamReader.ReadToEnd();
}
but it throws an exception:
"Cannot send a content-body with this verb-type."
If you use .NET core, the new HttpClient can handle this. Otherwise you can use System.Net.Http.WinHttpHandler package, but it has a ton of dependencies. See answer
https://stackoverflow.com/a/47902348/1030010
for how to use these two.
I can't use .NET core and I don't want to install System.Net.Http.WinHttpHandler.
I solved it by using reflection, to trick WebRequest that it is legal to send body with a GET request (which is according to latest RFC). What I do is to set ContentBodyNotAllowed to false for HTTP verb "GET".
var request = WebRequest.Create(requestUri);
request.ContentType = "application/json";
request.Method = "GET";
var type = request.GetType();
var currentMethod = type.GetProperty("CurrentMethod", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(request);
var methodType = currentMethod.GetType();
methodType.GetField("ContentBodyNotAllowed", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(currentMethod, false);
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
streamWriter.Write("<Json string here>");
}
var response = (HttpWebResponse)request.GetResponse();
Note, however, that the attribute ContentBodyNotAllowed belongs to a static field, so when its value changes, it remains in effect for the rest of the program. That's not a problem for my purposes.
It is entirely possible, but you have to use the newer HttpClient class: https://stackoverflow.com/a/47902348/70345
Even tho it is technically allowed to send a body with Get requests, Microsoft has decided for you that you cannot do that.
This can be seen in HttpWebRequest source code:
if (onRequestStream) {
// prevent someone from getting a request stream, if the protocol verb/method doesn't support it
throw new ProtocolViolationException(SR.GetString(SR.net_nouploadonget));
}
So you need to change your verb to Put or Post or have some other workaround.
GET will only receive it.
If you need to specify parameters, please include it in url.
Or you can send JSON BODY if POST or PUT.
HTTP request methods
HTTP defines a set of request methods to indicate the desired action to be performed for a given resource. Although they can also be nouns, these request methods are sometimes referred as HTTP verbs. Each of them implements a different semantic, but some common features are shared by a group of them: e.g. a request method can be safe, idempotent, or cacheable.
GET
The GET method requests a representation of the specified resource. Requests using GET should only retrieve data.
HEAD
The HEAD method asks for a response identical to that of a GET request, but without the response body.
POST
The POST method is used to submit an entity to the specified resource, often causing a change in state or side effects on the server.
PUT
The PUT method replaces all current representations of the target resource with the request payload.
In Addition:
I found this. Long discussion has been held.
HTTP GET with request body
What this means is that it is possible to send BODY with GET, but sending a payload body on a GET request might cause some existing implementations to reject the request (such as Proxy in the middle of the route).
Please be sure to read this article carefully as there are many other points to pay attention to.
By the way, it seems that you can send GET with body using the -i option of cURL command.
Curl GET request with json parameter
I'm trying to get data from the Microsoft Live API. However, when I try to get the access_token, I instead get a 415(Unsupported Media Type) error message. I have looked pretty much everywhere, but I can't find any answer (that worked for me).
Here is my (partial) code that tries to get the token (dataToWrite is cut-up for readability, it's one line in the actual code):
WebRequest request;
request = WebRequest.Create("https://login.live.com/oauth20_token.srf");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
var dataToWrite = "code=[code]&
client_id=[client_id]&
client_secret=[client_secret]&
redirect_uri=[redirect_uri]&
grant_type=authorization_code";
var buffer = Encoding.ASCII.GetBytes(dataToWrite);
request.ContentLength = buffer.Length;
var dataStream = request.GetRequestStream();
dataStream.Write(buffer, 0, buffer.Length);
dataStream.Close();
var response = request.GetResponse();
var responseStream = response.GetResponseStream();
Where the '[]' are:
[code] is a string, given by Microsoft after user logs in (this part of the code works);
[client_id] is a string, given by Microsoft, representing my client id;
[client_secret] is a string, given by Microsoft, representing my client secret;
[redirect_uri] is the URL of the site's return location (same as the URL used in the code for the user consent(see [code]))
According to the manual of Microsoft Live API(http://msdn.microsoft.com/en-us/library/live/hh243647.aspx) this should work. However, the documentation isn't very detailed.
Does anyone know why I keep getting the error?
Thanks!
Never mind, I'm an idiot...
It does work after all. I did another request after this one. And that one failed because I did not include the parameters there.
I'm working with google's OAuth api for web server applications, specifically asp.net mvc, and i'm able to get to the point where google returns an authorization code for a certain oauth request. At that point, I'm trying to obtain the access token using the following code:
public ActionResult GetOAuthToken()
{
HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(OAuthConfig.getTokenUrl(Request.QueryString["code"].ToString()));
myReq.Method = "POST";
myReq.Host = "accounts.google.com";
myReq.ContentType = "application/x-www-form-urlencoded";
WebResponse resp = myReq.GetResponse();
return View();
}
The OAuthConfig is just a class I wrote that contains a method getTokenUrl(), which returns a url with parameters such as code, client_secret, client_id etc. for the url: https://accounts.google.com/o/oauth2/token. I've debugged and checked that there's nothing wrong with this url.
I keep getting the following error: The remote server returned an error: (411) Length Required.
I don't know what to specify for the content length, or if there's something else that i need to include to fix this error?
Have you tried to have a look at Google-API .NET Client?
If you debug you will see Google uses "length" as an internal property when sending access-token request. you can try to fix it on your own, but you can use THEIR class in order to send the token request; If you use their class you do not have to worry about internal such as length...
First, check this message which I was trying to do:
Login
To log on to Windows8 service is through the URL: http://app.proceso.com.mx/win8/login
This URL HTTP Request Method receives POST variables user and pass. The variable user is the user's email and pass the variable is the same password. In the event that the user or password are invalid return plain text number zero 0, in the opposite case, that the username and password are valid return plain text an alphanumeric string of 32 characters, as this b17f27a16589fee247c666da6ed15569, this string is the hash of the valid user valid and will run from 00:00 hours to 23:59 hours the day it was generated.
To test the URL was created: http://app.proceso.com.mx/win8/login_test
Note: It should be clear that the hash generated will only be valid for Windows8 service to the user that gender and the effect from 00:00 hours to 23:59 on the day it was generated.
Note: All services generate text in UTF-8
Here is a test account:
User: javier.lopez.contreras10#gmail.com
Pass: policarpio20
So, if you set the data in this page: http://app.proceso.com.mx/win8/login_test you will receive a hash code.
And that's what I'm trying to accomplish in a metro application, but I feel lost in the situation. I have no idea to send those data to receive the hash code. I was using HttpClient and HttpContent but I'm not sure.
Thanks in advance.
UPDATE: Thanks to dharnitski for the code, right now I'm modifying this code for Win8 CP:
// this is what we are sending
string post_data = "user=javier.lopez.contreras10#gmail.com&pass=policarpio20";
// this is where we will send it
string uri = "http://app.proceso.com.mx/win8/login";
// create a request
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = "POST";
// turn our request string into a byte stream
byte[] postBytes = Encoding.UTF8.GetBytes(post_data);
// this is important - make sure you specify type this way
request.ContentType = "application/x-www-form-urlencoded";
Stream requestStream = await request.GetRequestStreamAsync();
// now send it
requestStream.Write(postBytes, 0, postBytes.Length);
// grab te response and print it out to the console along with the status code
WebResponse response = await request.GetResponseAsync();
//var a = new StreamReader(response.GetResponseStream()).ReadToEnd();
StreamReader requestReader = new StreamReader(response.GetResponseStream());
String webResponse = requestReader.ReadToEnd();
And I realized, HttpWebRequest does not contain ProtocolVersion and is throwing me this error in this line:
WebResponse response = await request.GetResponseAsync();
// ERROR: The remote server returned an error: (417) Expectation Failed.
How can I solve this problem if I can modify protocol version?
This is an sample code to implement HTTP POST in C#
http://www.terminally-incoherent.com/blog/2008/05/05/send-a-https-post-request-with-c/
IMPORTANT: You must switch your web page to HTTPS (SSL). It is very bad practice to send not encrypted passwords.