I want to make use of the hoopla-api which from their website uses "CURL" and I need to make HTTP "POST, GET" using C#.
They mention that any Questions related to development posted on stackoverflow but I didn't see any post from anyone who asked a question. or perhaps it is just too easy for many people to get this up.
Here is their link https://developer.hoopla.net/docs/authentication
I am not sure how to properly implement this in C#:
Below is my sample GET method.
string res;
string client_id = "myclientid";
string client_secret = "mysecret";
string auth = client_id + ":" + client_secret;
string ContentType = "application/json";
string url = #"https://api.hoopla.net/users";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "GET";
//request.Credentials = new NetworkCredential(client_id, client_secret);
request.Headers.Add("Authorization", "Bearer" + auth);
request.ContentType = ContentType;
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
using (Stream stream = response.GetResponseStream())
using (StreamReader reader = new StreamReader(stream))
{
res = reader.ReadToEnd();
}
and from their site they do have a python script that imports request module. but not sure if python has this module.
Here is their code :
import requests
client_id = 'your-generated-client-id'
client_secret = 'your-generated-client-secret'
host = 'https://api.hoopla.net'
auth_params = {'grant_type': 'client_credentials', 'client_id': client_id, 'client_secret': client_secret}
r = requests.post( host+'/oauth2/token', params = auth_params )
access_token = r.json()['access_token']
request_headers = {
'Authorization':'Bearer '+access_token,
'Accept':'application/vnd.hoopla.api-descriptor+json'
}
r = requests.get( host+'/',headers = request_headers )
}
Can anyone assist me in getting this in C#?
Related
I am a SQL Developer, JSON and C# are completely new to me. I am trying to get the JSON data from Rest API from elastic DB using POST method. I think my code is incorrect since I am getting all the response from the API even though I am passing string json variable in my c# code.
public static string COSMOS(string getAPiurl, string ApiUserId, string ApiPassword)
{
string url = getAPiurl;
HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create(url);
webrequest.Method = "POST";
webrequest.ContentType = "application/JSON";
webrequest.Accept = "application/JSON";
String username = ApiUserId;
String password = ApiPassword;
String encoded = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(username + ":" + password));
webrequest.Headers.Add("Authorization", "Basic " + encoded);
using (var streamWriter = new StreamWriter(webrequest.GetRequestStream()))
{
string json = "{\"query\":{\"bool\":{\"should\":[{\"match\":{\"platform\":{\"query\":\"COSMOS\"}}}],\"filter\":" +
"[{\"range\":{\"cu_ticketLastUpdated_date\":{\"gte\":\"2022-05-01 00:00:00\",\"lt\":" +
"\"2022-05-31 23:59:59\"}}}]}}}";
streamWriter.Write(json);
}
var httpResponse = (HttpWebResponse)webrequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var rl = streamReader.ReadToEnd();
httpResponse.Close();
}
I am using the above code in my SSIS script component. When I am trying to debug the above code in the var rl I am getting all the response even though I am passing the filters like "filter":[{"range":{"cu_ticketLastUpdated_date":{"gte":"2022-05-01 00:00:00","lt":"2022-05-31 23:59:59"}}
Please help me with an solution.
i am trying to send a POST request with body to WordPress API. I am still getting 401 error.
I decided to use: https://gist.github.com/DeskSupport/2951522 to authorize via OAuth 1.0 and it works perfectly with GET method. Then i wanted to implement another method which sends simple body.
That's my code:
var oauth = new OAuth.Manager();
oauth["consumer_key"] = _consumerKey;
oauth["consumer_secret"] = _consumerSecret;
oauth["token"] = _accessToken;
oauth["token_secret"] = _tokenSecret;
var appUrl = _baseUrl + url;
var authzHeader = oauth.GenerateAuthzHeader(appUrl, "POST");
string body = GenerateBody(parameters);
byte[] encodedData = Encoding.ASCII.GetBytes(body);
var request = (HttpWebRequest)WebRequest.Create(appUrl);
request.Method = "POST";
request.PreAuthenticate = true;
request.AllowWriteStreamBuffering = true;
request.Headers.Add("Authorization", authzHeader);
request.ContentLength = encodedData.Length;
request.ContentType = "application/x-www-form-urlencoded";
Stream newStream = request.GetRequestStream();
newStream.Write(encodedData, 0, encodedData.Length);
using (var response = (HttpWebResponse)request.GetResponse())
{
if (response.StatusCode != HttpStatusCode.OK)
{
}
}
The result of method GenerateBody is user_login=login&user_pass=BXE&04K44DoR1*a
I also tried to change the '&' character to '%26' but it didn't work.
This request works via Postman and i don;t know what's wrong.
OK, I found a solution.
https://blog.dantup.com/2016/07/simplest-csharp-code-to-post-a-tweet-using-oauth/
This guy wrote the way to make this request. What is also important you have to change a oauth_nonce for unique token.
After many struggles, I was finally able to get the OAuth Authentication/Refresh token process down. I am certain that the tokens I am using in this process are good. But I am struggling to communicate with the Compliance API and I think it may have more to do with my headers authentication process than it does specifically the Compliance API but I am not certain. I've tried so many different combinations of the below code unsuccessfully. I've tried to do the call as a GET and a POST (the call should be a GET). I've tried it with the access token encoded and not encoded. With all of my different code combinations tried I've been getting either an authorization error or a bad request error. You can see some of the various things I've tried from commented out code. Thank you for your help.
public static string Complaince_GetViolations(string clientId, string ruName, string clientSecret, string accessToken, ILog log)
{
var clientString = clientId + ":" + clientSecret;
//byte[] clientEncode = Encoding.UTF8.GetBytes(clientString);
//var credentials = "Basic " + System.Convert.ToBase64String(clientEncode);
byte[] clientEncode = Encoding.UTF8.GetBytes(accessToken);
var credentials = "Bearer " + System.Convert.ToBase64String(clientEncode);
var codeEncoded = System.Web.HttpUtility.UrlEncode(accessToken);
HttpWebRequest request = WebRequest.Create("https://api.ebay.com/sell/compliance/v1/listing_violation?compliance_type=PRODUCT_ADOPTION")
as HttpWebRequest;
request.Method = "GET";
// request.ContentType = "application/x-www-form-urlencoded";
//request.Headers.Add(HttpRequestHeader.Authorization, credentials);
//request.Headers.Add(HttpRequestHeader.Authorization, "Bearer " + codeEncoded);
request.Headers.Add(HttpRequestHeader.Authorization, credentials);
//request.Headers.Add("Authorization", "Bearer " + codeEncoded);
request.Headers.Add("X-EBAY-C-MARKETPLACE-ID", "EBAY-US");
log.Debug("starting request.GetRequestStream");
string result = "";
var response = (HttpWebResponse)request.GetResponse();
using (var streamReader = new StreamReader(response.GetResponseStream())) //FAILS HERE
{
result = streamReader.ReadToEnd();
}
//DO MORE STUFF BELOW
return "STUFF";
}
And I finally figured out a resolution to this problem. The HTML encoding of the entire bearer string was the issue. If anyone needs this in the future your welcome. =)
HttpWebRequest request = WebRequest.Create("https://api.ebay.com/sell/compliance/v1/listing_violation?compliance_type=PRODUCT_ADOPTION")
as HttpWebRequest;
request.Method = "GET";
request.Headers.Add(HttpRequestHeader.Authorization, System.Web.HttpUtility.HtmlEncode("Bearer " + accessToken));
request.Headers.Add("X-EBAY-C-MARKETPLACE-ID", "EBAY-US");
log.Debug("starting request.GetRequestStream");
string result = null;
var response = (HttpWebResponse)request.GetResponse();
using (var streamReader = new StreamReader(response.GetResponseStream()))
{
result = streamReader.ReadToEnd();
}
I am trying to use the API against our ALM 12.21 server, but always ends up with "401 Unauthorized". It seems that I get the auth cookie back correctly, but when I try to do something after that I am unauthorized.
I use this the get this to get auth cookie (seems to work):
HttpWebRequest myauthrequest = (HttpWebRequest)WebRequest.Create("https://server/qcbin/authentication-point/alm-authenticate");
string AuthenticationXML = #"<alm-authentication>
<user>username</user>
<password>password</password>
</alm-authentication>";
byte[] Requestbytes = Encoding.UTF8.GetBytes(AuthenticationXML);
myauthrequest.Method = "POST";
myauthrequest.ContentType = "application/xml";
myauthrequest.ContentLength = Requestbytes.Length;
myauthrequest.Accept = "application/xml";
Stream RequestStr = myauthrequest.GetRequestStream();
RequestStr.Write(Requestbytes, 0, Requestbytes.Length);
RequestStr.Close();
HttpWebResponse myauthres = (HttpWebResponse)myauthrequest.GetResponse();
var AuthenticationCookie = myauthres.Headers.Get("Set-Cookie");
AuthenticationCookie = AuthenticationCookie.Replace(";Path=/;HTTPOnly", "");
I am not sure if the .Replace is needed. Just read it somewhere. I get 401 both with or without it though, when trying to do subsequent requests.
Trying e.g. this after getting auth cookie:
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("https://server/qcbin/rest/domains/FS/projects/P3602_SLS_Project/defects/1");
req.Method = "GET";
req.ContentType = "application/xml";
req.Accept = "application/octet-stream";
req.Headers.Set(HttpRequestHeader.Cookie, AuthenticationCookie);
HttpWebResponse res = (HttpWebResponse)req.GetResponse();
Stream RStream2 = res.GetResponseStream();
XDocument doc = XDocument.Load(RStream2);
Which fails with 401.
Anyone have complete working code for the ALM 12.21 REST API?
You need two main cookies to get the ALM REST API works perfectly.
LWSSO_COOKIE_KEY
QCSession
almURL = "https://..com/qcbin/"
authEndPoint = almURL + "authentication-point/authenticate"
qcSessionEndPoint = almURL + "rest/site-session"
After you get successful response for authEndPoint you will get the LWSSO_COOKIE_KEY
Use that cookie in your next request to qcSessionEndPoint, it should give you QCSession cookie.
Use both LWSSO_COOKIE_KEY and QCSession cookies in your subsequent requests to get data from ALM.
I see that you are using octet-stream to get the defect response. When I checked the documentation, it can return one of the following types.
"application/xml"
"application/atom+xml"
"application/json"
Just in case, if you need to see some working implementation in python, here it is https://github.com/macroking/ALM-Integration/blob/master/ALM_Integration_Util.py
It may give you some idea.
Thank you #Barney. You sent me in the correct direction :-) For anyone interested, I managed it like this, e.g. for getting defect ID 473:
Logging on to create a CookieContainer and then use that to do the actual ALM data fetch:
private void button1_Click(object sender, EventArgs e)
{
string almURL = #"https://url/qcbin/";
string domain = "domain";
string project = "project";
CookieContainer cookieContainer = LoginAlm2(almURL, "username", "password", domain, project);
HttpWebRequest myWebRequest1 = (HttpWebRequest)WebRequest.Create(almURL + "/rest/domains/" + domain + "/projects/" + project + "/defects/473");
myWebRequest1.CookieContainer = cookieContainer;
myWebRequest1.Accept = "application/json";
WebResponse webResponse1 = myWebRequest1.GetResponse();
StreamReader reader = new StreamReader(webResponse1.GetResponseStream());
string res = reader.ReadToEnd();
}
public CookieContainer LoginAlm2(string server, string user, string password, string domain, string project)
{
//Creating the WebRequest with the URL and encoded authentication
string StrServerLogin = server + "/api/authentication/sign-in";
HttpWebRequest myWebRequest = (HttpWebRequest)WebRequest.Create(StrServerLogin);
myWebRequest.Headers[HttpRequestHeader.Authorization] = "Basic " + Base64Encode(user + ":" + password);
WebResponse webResponse = myWebRequest.GetResponse();
CookieContainer c = new CookieContainer();
Uri uri = new Uri(server);
string StrCookie = webResponse.Headers.ToString();
string StrCookie1 = StrCookie.Substring(StrCookie.IndexOf("LWSSO_COOKIE_KEY=") + 17);
StrCookie1 = StrCookie1.Substring(0, StrCookie1.IndexOf(";"));
c.Add(new Cookie("LWSSO_COOKIE_KEY", StrCookie1) { Domain = uri.Host });
//Then the QCSession cookie
string StrCookie2 = StrCookie.Substring(StrCookie.IndexOf("QCSession=") + 10);
StrCookie2 = StrCookie2.Substring(0, StrCookie2.IndexOf(";"));
c.Add(new Cookie("QCSession", StrCookie2) { Domain = uri.Host });
//Then the ALM_USER cookie
string StrCookie3 = StrCookie.Substring(StrCookie.IndexOf("ALM_USER=") + 9);
StrCookie3 = StrCookie3.Substring(0, StrCookie3.IndexOf(";"));
c.Add(new Cookie("ALM_USER", StrCookie3) { Domain = uri.Host });
//And finally the XSRF-TOKEN cookie
string StrCookie4 = StrCookie.Substring(StrCookie.IndexOf("XSRF-TOKEN=") + 12);
StrCookie4 = StrCookie4.Substring(0, StrCookie4.IndexOf(";"));
c.Add(new Cookie("XSRF-TOKEN", StrCookie4) { Domain = uri.Host });
return c;
}
Works like a charm :-)
I want to authenticate the users who visit my website using google's OAUTH2.0.
I have successfully got the authorization_code in response and now I am facing problem when I make a 'POST request' to Google when getting an access token. The problem is that the request is being continued over the time and I'm not getting any response.
Is there anything wrong in the code I have written below?
StringBuilder postData = new StringBuilder();
postData.Append("code=" + Request.QueryString["code"]);
postData.Append("&client_id=123029216828.apps.googleusercontent.com");
postData.Append("&client_secret=zd5dYB9MXO4C5vgBOYRC89K4");
postData.Append("&redirect_uri=http://localhost:4180/GAuth.aspx&grant_type=authorization_code");
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://accounts.google.com/o/oauth2/token?code=" + Request.QueryString["code"] + "&client_id=124545459218.apps.googleusercontent.com&client_secret={zfsgdYB9MXO4C5vgBOYRC89K4}&redirect_uri=http://localhost:4180/GAuth.aspx&grant_type=authorization_code");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
string addons = "/o/oauth2/token?code=" + Request.QueryString["code"] + "&client_id=123029216828.apps.googleusercontent.com&client_secret={zd5dYB9MXO4C5vgBOYRC89K4}&redirect_uri=http://localhost:4180/GAuth.aspx&grant_type=authorization_code";
request.ContentLength = addons.Length;
Stream str = request.GetResponse().GetResponseStream();
StreamReader r = new StreamReader(str);
string a = r.ReadToEnd();
str.Close();
r.Close();
As I mentioned in my comment, you just have a few minor mistakes in your code. As it stands, you're not actually POST-ing anything. I'm assuming you intend to send the postData string.
The following should work:
//Build up your post string
StringBuilder postData = new StringBuilder();
postData.Append("code=" + Request.QueryString["code"]);
postData.Append("&client_id=123029216828.apps.googleusercontent.com");
postData.Append("&client_secret=zd5dYB9MXO4C5vgBOYRC89K4");
postData.Append("&redirect_uri=http://localhost:4180/GAuth.aspx&grant_type=authorization_code");
//Create a POST WebRequest
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://accounts.google.com/o/oauth2/token?code=" + Request.QueryString["code"] + "&client_id=124545459218.apps.googleusercontent.com&client_secret={zfsgdYB9MXO4C5vgBOYRC89K4}&redirect_uri=http://localhost:4180/GAuth.aspx&grant_type=authorization_code");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
//Write your post string to the body of the POST WebRequest
var sw = new StreamWriter(request.GetRequestStream());
sw.Write(postData.ToString());
sw.Close();
//Get the response and read it
var response = request.GetResponse();
var raw_result_as_string = (new StreamReader(response.GetResponseStream())).ReadToEnd();
You were just missing the part where you attached the string to your POST WebRequest.