I try to use FRED with Hammock to use the provided REST service. unfortunately I have no idea how to use it.
what I did so far:
string url = "http://wit.istc.cnr.it/stlab-tools/fred/api";
Hammock.RestClient client = new Hammock.RestClient();
client.AddHeader("Accept", "image/png -F text=Miles Davis was an american jazz musician");
//client.AddHeader("Accept", "text=Miles Davis was an american jazz musician");
client.Authority = url;
Hammock.RestRequest req = new Hammock.RestRequest();
req.Path = url;
Hammock.RestResponse response = client.Request(req);
string _result = client.Request(req).Content;
You're making a POST request but you never specify that.
From juniper.net, an extract to make POST Request:
public void makeQRest() {
try {
string auth = "http://wit.istc.cnr.it/stlab-tools/fred/api";
string body = "text=Miles Davis was an american jazz musician";
IWebCredentials credentials = new Hammock.Authentication.Basic.BasicAuthCredentials {
Username = Config.uName,
Password = Config.pWord
};
RestClient client = new RestClient {
Authority = auth,
};
client.AddHeader("content-type", "Accept: image/png");
RestRequest request = new RestRequest {
Credentials = credentials,
Method = WebMethod.Post
};
request.AddPostContent(Encoding.UTF8.GetBytes(body));
RestResponse response = client.Request(request);
Console.WriteLine("the create Queue status is " + response.StatusCode);
Console.WriteLine(response.Content);
Console.ReadLine();
} catch (Exception e) {
Console.WriteLine(e.Message);
Console.ReadLine();
}
}
The Method = WebMethod.Post part is the first missing thing in your code.
Related
I can't manage to stablish a connection to Synology NAS from c# using RestSharp (or any other method)
public void TryConnection()
{
var request = new RestRequest("/webapi/entry.cgi", Method.Post);
request.AddParameter("path", "entry.cgi");
request.AddParameter("api", "SYNO.API.Info");
request.AddParameter("version", "1");
request.AddParameter("method", "query");
var client = new RestClient(new RestClientOptions("http://quickconnect.to/FDesign-GmbH:5000/") { FollowRedirects = true });
var response = client.ExecuteGetAsync(request).Result;
string s = response.ResponseUri.ToString();
}
Result = "Request failed with status code Redirect".
from what i found i believe this is having something to do with redirects but i dont know how to handle it...
if i paste this Url manualy in browser i get feedback :
https://192-168-178-23.fdesign-gmbh.direct.quickconnect.to:5001/webapi/entry.cgi?api=SYNO.API.Info&version=1&method=query
same Url in Code:
public void TryConnection()
{
var request = new RestRequest("/webapi/entry.cgi", Method.Post);
//request.AddParameter("path", "entry.cgi");
request.AddParameter("api", "SYNO.API.Info");
request.AddParameter("version", "1");
request.AddParameter("method", "query");
request.AddParameter("query", "SYNO.API.Auth,SYNO.FileStation");
var client = new RestClient(new RestClientOptions("https://192-168-178-23.fdesign-gmbh.direct.quickconnect.to:5001/") { FollowRedirects = false });
var response = client.ExecuteGetAsync(request).Result;
string s = response.ResponseUri.ToString();
}
with code i get : "Error sending request"
Some help on this would be appreciated.
Just started at a new company and we all use Jira, the customers are determined to not use it as they don't like it so I have decided to build a simple Windows Form when they can both Log tickets and get Updates and Comments in a nice simple UI.
Now I have never done any coding before 2 weeks ago so it has been a struggle to get my head around both C# and Rest (Have made scripts for basic IT fixes but never anything as complex as this!)
Back onto point, Set up and got a Rest API set up with a Rest Client but everytime I try pull data from a ticket on Jira I get the error:
{"errorMessages":["You do not have the permission to see the specified issue.","Login Required"],"errors":{}}
Here is the code from the Form:
private void button3_Click_1(object sender, EventArgs e)
{
var client = new RestClient("https://jira.eandl.co.uk/rest/api/2/issue/ITREQ-" + textBox1.Text
);
client.Authenticator = new SimpleAuthenticator("username", "abc", "password", "123");
var request = new RestRequest(Method.GET);
request.AddParameter("token", "saga001", ParameterType.UrlSegment);
// request.AddUrlSegment("token", "saga001");
request.OnBeforeDeserialization = resp => { resp.ContentType = "application/json"; };
var queryResult = client.Execute(request);
Console.WriteLine(queryResult.Content);
}
And here is the code from the Rest Client itself:
public Restclient()
{
endPoint = string.Empty;
httpMethod = httpVerb.GET;
}
private string logonAttempt;
public string makeRequest()
{
string strResponseValue = string.Empty;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(endPoint);
request.Method = httpMethod.ToString();
String authHeader = System.Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(userName + ":" + userPassword));
request.Headers.Add("Authorization", authType.ToString() + " " + authHeader);
HttpWebResponse response = null;
try
{
response = (HttpWebResponse)request.GetResponse();
//Process the Response Stream... (Could be JSON, XML ot HTML etc...)
using (Stream responseStream = response.GetResponseStream())
{
if (responseStream != null)
{
using (StreamReader reader = new StreamReader(responseStream))
{
strResponseValue = reader.ReadToEnd();
}//End of Stream Reader
}
}//end of Response Stream
}
catch (Exception ex)
{
strResponseValue = "(\"errorMessages\":[\"" + ex.Message.ToString() + "\"],\"errors\":{}}";
}
finally
{
if(response != null)
{
((IDisposable)response).Dispose();
}
}
return strResponseValue;
}
}
}
Now obviously I am expecting that I have missed something absolutely bigginer as like I said, I've never taken on a project like this before and had 0 experience.
Just looking for someone to bluntly tell me what I'm doing wrong
Changed to this as per answer:
private void button3_Click_1(object sender, EventArgs e)
{
var client = new
RestClient("https://jira.eandl.co.uk/rest/api/2/issue/ITREQ-" + textBox1.Text
);
client.Authenticator = new HttpBasicAuthenticator("username", "password");
var request = new RestRequest(Method.GET);
string authHeader = Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes("cdale!" + ":" + "Chantelle95!"));
request.AddHeader("Authorization", "Basic " + authHeader);
request.OnBeforeDeserialization = resp => { resp.ContentType = "application/json"; };
var queryResult = client.Execute(request);
Console.WriteLine(queryResult.Content);
}
By default with the Jira REST API, you can use Basic Authentication or OAuth2. I think that more easy way for you will be to use the Basic one.
I'm not sure why you have a class where you define your custom RestClient since the first block of code uses the RestSharp one from http://restsharp.org.
In this case, you will need to modify your authenticator:
client.Authenticator = new HttpBasicAuthenticator(userName, password);
And I think that you should remove the line where you specify a token. I don't think that it's required.
Finally, the class Restclient doesn't seem to be used, then remove it.
You could also uses what you have created in your custom RestClient and manually specify a Basic header:
string authHeader = Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(userName + ":" + userPassword));
request.AddHeader("Authorization", "Basic " + authHeader);
However, it's essentially the behavior of the HttpBasicAuthenticator class.
If you don't want to encode your credentials in every request here is how to do it using cookies.
When requesting the cookie you don't need to add any authorization on the headers. This method will accept a JSON string with the user name and password and the URL. It will return the cookie values.
public async Task<JiraCookie> GetCookieAsync(string myJsonUserNamePassword, string JiraCookieEndpointUrl)
{
using (var client = new HttpClient())
{
var response = await client.PostAsync(
JiraCookieEndpointUrl,
new StringContent(myJsonUserNamePassword, Encoding.UTF8, "application/json"));
var json = response.Content.ReadAsStringAsync().Result;
var jiraCookie= JsonConvert.DeserializeObject<JiraCookie>(json);
return jArr;
}
}
public class JiraCookie
{
public Session session { get; set; }
}
public class Session
{
public string name { get; set; }
public string value { get; set; }
}
When I call it using url: http://[baseJiraUrl]/rest/auth/1/session it returns the following JSON response:
{
"session" : -{
"name" : JSESSIONID,
"value" : cookieValue
}
Keep in mind the URL above is valid in the version of JIRA I'm using and may vary depending on which version you're using. Read the JIRA API documentation for the correct URL for the version you are using. I'm using the following:
https://docs.atlassian.com/software/jira/docs/api/REST/7.6.1/#auth/1/session
Remember you'll have to store your cookie and use it on every subsequent request.
Check out this answer on how add cookies to your HttpClient request: How do I set a cookie on HttpClient's HttpRequestMessage.
Once you're done with the cookie (logging out) simply send a delete http request with the same URL as the post.
Reference: https://stackoverflow.com/a/49109192/7763903
I am a newbie to Mailgun and REST and need some help.
If I use the Mailgun provided code:
RestClient client = new RestClient();
client.BaseUrl = "https://api.mailgun.net/v2";
client.Authenticator = new HttpBasicAuthenticator("api", "xxxx");
RestRequest request = new RestRequest();
request.Resource = "/address/validate";
request.AddParameter("address", "me#mydomain.com");
return client.Execute(request);
How do I retrieve and process the response that the address is valid or not?
This code works for me. I didn't use RESTClient and wrote my own code(which works perfectly fine)
[System.Web.Services.WebMethod]
public static object GetEmailInfo(string UserName)
{
var http = (HttpWebRequest)WebRequest.Create("https://api.mailgun.net/v2/address/validate?address=" + UserName);
http.Credentials = new NetworkCredential("api","public key");
http.Timeout = 5000;
try
{
var response = http.GetResponse();
var stream = response.GetResponseStream();
var sr = new StreamReader(stream);
var content = sr.ReadToEnd();
JSON.JsonObject js = new JSON.JsonObject(content);
return Convert.ToBoolean(js["is_valid"]);
}
catch (Exception ex)
{
}
}
First of You should never post private information such as your public key of such API
Just by using the amazing Postman Chrome app you can see the result of such request:
click here to see the image below in full resolution
and I'm sure, if you instead of return client.Execute(request); you do
var result = client.Execute(request);
return result;
and adding a breakpoint in the return you can inspect what is the object that is passed from the call... without testing, I'm sure you can convert result.Content (as it's where RestSharp appends the response content) into an object and use that object (or use the dynamic type).
now, testing your code in VS:
click here to see the image below in full resolution
you can then use the dynamic object like:
click here to see the image below in full resolution
public void GetResponse()
{
var client = new RestClient();
client.BaseUrl = "https://api.mailgun.net/v2";
client.Authenticator = new HttpBasicAuthenticator("api", "pubkey-e82c8201c292691ad889ace3434df6cb");
var request = new RestRequest();
request.Resource = "/address/validate";
request.AddParameter("address", "me#mydomain.com");
var response = client.Execute(request);
dynamic content = Json.Decode(response.Content);
bool isValid = content.is_valid;
string domain = content.parts.domain;
}
and treat the content of the response just like the json passed:
{
"address": "me#mydomain.com",
"did_you_mean": null,
"is_valid": true,
"parts": {
"display_name": null,
"domain": "mydomain.com",
"local_part": "me"
}
}
I'm trying to call Paypal api from my code. I set up the sandbox account and it works when I use curl but my code isn't working the same way, returning 401 Unauthorized instead.
Here's the curl command as documented by Paypal
curl https://api.sandbox.paypal.com/v1/oauth2/token -H "Accept: application/json" -H "Accept-Language: en_US" -u "A****:E****" -d "grant_type=client_credentials"
UPDATE: Apparently the .Credentials doesn't do the trick, instead setting Authorization header manually works (see code)
Here's the code (trimmed to its essence):
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("https://api.sandbox.paypal.com/v1/oauth2/token");
request.Method = "POST";
request.Accept = "application/json";
request.Headers.Add("Accept-Language:en_US")
// this doesn't work:
**request.Credentials = new NetworkCredential("A****", "E****");**
// DO THIS INSTEAD
**string authInfo = Convert.ToBase64String(System.Text.Encoding.Default.GetBytes("A****:E****"));**
**request.Headers["Authorization"] = "Basic " + authInfo;**
using (StreamWriter swt = new StreamWriter(request.GetRequestStream()))
{
swt.Write("grant_type=client_credentials");
}
request.BeginGetResponse((r) =>
{
try
{
HttpWebResponse response = request.EndGetResponse(r) as HttpWebResponse; // Exception here
....
} catch (Exception x) { .... } // log the exception - 401 Unauthorized
}, null);
This is the request from code captured by Fiddler (raw), there are no authorization parameters for some reason:
POST https://api.sandbox.paypal.com/v1/oauth2/token HTTP/1.1
Accept: application/json
Accept-Language: en_US
Host: api.sandbox.paypal.com
Content-Length: 29
Expect: 100-continue
Connection: Keep-Alive
grant_type=client_credentials
Hoping the following code help to anyone who is still looking for a good piece of cake to get connected to PayPal.
As many people, I've been investing a lot of time trying to get my PayPal token access without success, until I found the following:
public class PayPalClient
{
public async Task RequestPayPalToken()
{
// Discussion about SSL secure channel
// http://stackoverflow.com/questions/32994464/could-not-create-ssl-tls-secure-channel-despite-setting-servercertificatevalida
ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
try
{
// ClientId of your Paypal app API
string APIClientId = "**_[your_API_Client_Id]_**";
// secret key of you Paypal app API
string APISecret = "**_[your_API_secret]_**";
using (var client = new System.Net.Http.HttpClient())
{
var byteArray = Encoding.UTF8.GetBytes(APIClientId + ":" + APISecret);
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
var url = new Uri("https://api.sandbox.paypal.com/v1/oauth2/token", UriKind.Absolute);
client.DefaultRequestHeaders.IfModifiedSince = DateTime.UtcNow;
var requestParams = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("grant_type", "client_credentials")
};
var content = new FormUrlEncodedContent(requestParams);
var webresponse = await client.PostAsync(url, content);
var jsonString = await webresponse.Content.ReadAsStringAsync();
// response will deserialized using Jsonconver
var payPalTokenModel = JsonConvert.DeserializeObject<PayPalTokenModel>(jsonString);
}
}
catch (System.Exception ex)
{
//TODO: Log connection error
}
}
}
public class PayPalTokenModel
{
public string scope { get; set; }
public string nonce { get; set; }
public string access_token { get; set; }
public string token_type { get; set; }
public string app_id { get; set; }
public int expires_in { get; set; }
}
This code works pretty well for me, hoping for you too. The credits belong to Patel Harshal who posted his solution here.
This Works using HttpClient...
'RequestT' is a generic for the PayPal request arguments, however it is not used. The 'ResponseT' is used and it is the response from PayPal according to their documentation.
'PayPalConfig' class reads the clientid and secret from the web.config file using ConfigurationManager.
The thing to remember is to set the Authorization header to "Basic" NOT "Bearer" and if and to properly construct the 'StringContent' object with right media type (x-www-form-urlencoded).
//gets PayPal accessToken
public async Task<ResponseT> InvokePostAsync<RequestT, ResponseT>(RequestT request, string actionUrl)
{
ResponseT result;
// 'HTTP Basic Auth Post' <http://stackoverflow.com/questions/21066622/how-to-send-a-http-basic-auth-post>
string clientId = PayPalConfig.clientId;
string secret = PayPalConfig.clientSecret;
string oAuthCredentials = Convert.ToBase64String(Encoding.Default.GetBytes(clientId + ":" + secret));
//base uri to PayPAl 'live' or 'stage' based on 'productionMode'
string uriString = PayPalConfig.endpoint(PayPalConfig.productionMode) + actionUrl;
HttpClient client = new HttpClient();
//construct request message
var h_request = new HttpRequestMessage(HttpMethod.Post, uriString);
h_request.Headers.Authorization = new AuthenticationHeaderValue("Basic", oAuthCredentials);
h_request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
h_request.Headers.AcceptLanguage.Add(new StringWithQualityHeaderValue("en_US"));
h_request.Content = new StringContent("grant_type=client_credentials", UTF8Encoding.UTF8, "application/x-www-form-urlencoded");
try
{
HttpResponseMessage response = await client.SendAsync(h_request);
//if call failed ErrorResponse created...simple class with response properties
if (!response.IsSuccessStatusCode)
{
var error = await response.Content.ReadAsStringAsync();
ErrorResponse errResp = JsonConvert.DeserializeObject<ErrorResponse>(error);
throw new PayPalException { error_name = errResp.name, details = errResp.details, message = errResp.message };
}
var success = await response.Content.ReadAsStringAsync();
result = JsonConvert.DeserializeObject<ResponseT>(success);
}
catch (Exception)
{
throw new HttpRequestException("Request to PayPal Service failed.");
}
return result;
}
IMPORTANT: use Task.WhenAll() to ensure you have a result.
// gets access token with HttpClient call..and ensures there is a Result before continuing
// so you don't try to pass an empty or failed token.
public async Task<TokenResponse> AuthorizeAsync(TokenRequest req)
{
TokenResponse response;
try
{
var task = new PayPalHttpClient().InvokePostAsync<TokenRequest, TokenResponse>(req, req.actionUrl);
await Task.WhenAll(task);
response = task.Result;
}
catch (PayPalException ex)
{
response = new TokenResponse { access_token = "error", Error = ex };
}
return response;
}
Paypal has deprecated TLS 1.1, and only accepts 1.2 now. Unfortunately .NET (prior to version 4.7) uses 1.1 by default, unless you configure it otherwise.
You can turn on TLS 1.2 with this line. I recomend placing it Application_Start or global.asax.
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
I too suffered from a lack of example code and various issues with response errors and codes.
I am a big fan of RestClient as it helps a lot with integrations and the growing number of RESTful API calls.
I hope this small snippet of code using RestSharp helps someone: -
if (ServicePointManager.SecurityProtocol != SecurityProtocolType.Tls12) ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; // forced to modern day SSL protocols
var client = new RestClient(payPalUrl) { Encoding = Encoding.UTF8 };
var authRequest = new RestRequest("oauth2/token", Method.POST) {RequestFormat = DataFormat.Json};
client.Authenticator = new HttpBasicAuthenticator(clientId, secret);
authRequest.AddParameter("grant_type","client_credentials");
var authResponse = client.Execute(authRequest);
// You can now deserialise the response to get the token as per the answer from #ryuzaki
var payPalTokenModel = JsonConvert.DeserializeObject<PayPalTokenModel>(authResponse.Content);
I am developing social networks integration for my asp.net mvc4 application.
Twitter and Facebook were very easy for me but I am seriously stuck with LinkedIn.
Here is my code.
public ActionResult LinkedInTest(string text)
{
var client = new RestClient
{
Authority = "https://api.linkedin.com/uas/oauth",
Credentials = LinkedInSocialHelper.GetCredentials()
};
var request = new RestRequest {Path = "requestToken"};
RestResponse response = client.Request(request);
token = response.Content.Split('&')[0].Split('=')[1];
tokenSecret = response.Content.Split('&')[1].Split('=')[1];
textToPost = text;
Response.Redirect("https://api.linkedin.com/uas/oauth/authorize?oauth_token=" + token + "&scope=r_basicprofile+r_emailaddress+r_network+r_contactinfo+rw_nus");
return null;
textToPost = text;
return RedirectToAction("LinkedInCallback");
}
public ActionResult LinkedInCallback()
{
verifier = Request["oauth_verifier"];
var client = new RestClient
{
Authority = "https://api.linkedin.com/uas/oauth",
Credentials = LinkedInSocialHelper.GetCredentials(token, tokenSecret, verifier),
Method = WebMethod.Post
};
var request = new RestRequest {Path = "accessToken"};
RestResponse response = client.Request(request);
token = response.Content.Split('&')[0].Split('=')[1];
tokenSecret = response.Content.Split('&')[1].Split('=')[1];
LinkedInSocialHelper.Post(textToPost, token, tokenSecret);
return RedirectToAction("Calendar");
}
public static void Post(string text, string accessToken, string accessTokenSecret)
{
var tokenManager = new TokenManager(ApiKey, ApiSecret);
tokenManager.ExpireRequestTokenAndStoreNewAccessToken(null, null, accessToken, accessTokenSecret);
var authorization = new WebOAuthAuthorization(tokenManager, UserToken);
LinkedInService service = new LinkedInService(authorization);
//var user = service.GetCurrentUser(ProfileType.Public); - IT IS GIVING ME THE SAME ERROR - Access denied
service.CreateShare(text, VisibilityCode.ConnectionsOnly);
}
Everything works fine except last thing - posting shares - I get Access to posting shares denied exception despite the fact that I generate token using all the necessary permissions:
"https://api.linkedin.com/uas/oauth/authorize?oauth_token=" + token + "&scope=r_basicprofile+r_emailaddress+r_network+r_contactinfo+rw_nus"
Hope you good guys help me.
See the last post here - it describes how to solve it
https://developer.linkedin.com/forum/permission-scope-request-token-query-not-working?page=1