How to create a post to LinkedIn - c#

We are getting a HTTP error 400 Bad Request while creating the Post in linkedin using HTTP POST request.
Sample COde:
public static bool PostLinkedInNetworkUpdate(string accessToken, string title, string submittedUrl = "", string submittedImageUrl = "")
{
var requestUrl = String.Format(linkedinSharesEndPoint, accessToken);
var message = new
{
comment = "Testing out the LinkedIn Share API with JSON",
content = new Dictionary<string, string>
{ { "title", title },
{ "submitted-url", submittedUrl },
{"submitted-image-url" , submittedImageUrl}
},
visibility = new
{
code = "anyone"
}
};
var requestJson = new JavaScriptSerializer().Serialize(message);
var client = new WebClient();
var requestHeaders = new NameValueCollection
{
{ "Content-Type", "application/json" },
{ "x-li-format", "json" },
{"Host", "api.linkedin.com"}
};
client.Headers.Add(requestHeaders);
var responseJson = client.UploadString(requestUrl, "POST", requestJson);
var response = new JavaScriptSerializer().Deserialize<Dictionary<string, object>>(responseJson);
return response.ContainsKey("updateKey");
}
}
We are getting an error message on the line:
var responseJson = client.UploadString(requestUrl, "POST", requestJson);
as HTTP Error 400 Bad Request.
We have tested the code with GET Request which is working from my Dev server,However any of the POST requests are failing with this error message.
We have verified the REsponse headers with the request made from POSTMAN which is working.The response headers of POSTMAN are matching with the Bad Request response
Do we need to install the LinkedIn certificate in the Server?
Does anyone have any suggestions/comments?
Thanks in advance

Related

C# - Problems on Connect to Synology NAS with Restsharp

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.

RestSharp: Error "expected type: JSONObject, found: Null"

I am using RestSharp library for my REST APIs, and I am getting 400 BadRequest "expected type: JSONObject, found: Null" for GET request. With Postman it is working fine.
{
"Result": {
"RequestId": "495f45c0-d9e9-11eb-9936-02a74f481686",
"OverallStatus": "FAILURE",
"ErrorDetails": [
{
"ErrorLineItem": {
"ErrorCode": "400",
"ErrorMessage": "Bad Request",
"ErrorDescription": "expected type: JSONObject, found: Null"
}
}
]
}
}
Below is my code:
var request = new GetAlertProfileDistributionChannelRequest
{
AccountCustomerNumber = "*****201",
DistributionChannelSubscriptions = new AlertProfileDistributionChannelSubscriptions
{
AlertProfileId = Guid.Parse("7adaaa2c-5b2d-424c-8dc8-4e9a01908729")
}
};
var client = new RestClient("https://******/v1/profile/channels")
{
Timeout = -1
};
var apiRequest = new RestRequest(Method.GET) { RequestFormat = DataFormat.Json };
apiRequest.AddHeader("client_id", "********4cedc");
apiRequest.AddHeader("client_secret", "*******d526c");
apiRequest.AddHeader("Authorization", $"Bearer eyJhbGciOiJSUzI*******");
apiRequest.AddHeader("Content-Type", "application/json");
apiRequest.AddParameter("application/json", JsonConvert.SerializeObject(request), ParameterType.RequestBody);
var apiResponse = client.ExecuteAsync(apiRequest).Result;
Console.WriteLine(apiResponse.Content);
With Postman it is working fine:
Am I missing something here?
I resolved my issue with System.Net.Http.WinHttpHandler package that does support the functionality - simply installed and used when constructing my HttpClient instances.
var request = new GetAlertProfileDistributionChannelRequest
{
AccountCustomerNumber = "***0201",
DistributionChannelSubscriptions = new AlertProfileDistributionChannelSubscriptions
{
AlertProfileId = Guid.Parse("7adaaa2c-5b2d-424c-8dc8-4e9a01908729")
}
};
var handler = new WinHttpHandler();
var client = new HttpClient(handler);
client.DefaultRequestHeaders.Add("client_id", "**********5487");
client.DefaultRequestHeaders.Add("client_secret", "*******c99");
client.DefaultRequestHeaders.Add("Authorization", "Bearer eyJhbGciOiJSU");
var apirequest = new HttpRequestMessage
{
Method = HttpMethod.Get,
RequestUri = new Uri("https://*********profile/channels"),
Content = new StringContent(JsonConvert.SerializeObject(request), Encoding.UTF8, "application/json"),
};
var response = client.SendAsync(apirequest).Result;
response.EnsureSuccessStatusCode();
var result = response.Content.ReadAsStringAsync().Result;

How to send post request of Messaging API

What I want to do
I want to send "post request" following the link below. More specifically, when you open the link, you can see "Example request" which goes like this.
'{
"messages":[
{
"type":"text",
"text":"Hello, world1"
},
{
"type":"text",
"text":"Hello, world2"
}
]
}'
In sample it sends two messages but, I just want to send one.
I don't know how to write in C#
Send broadcast message
This is the code where I'm struggling.
// To creat HttpClient
var client = new HttpClient();
// Accesstoken
var accessToken = "my token";
// URL
var url = "https://api.line.me/v2/bot/message/broadcast";
var request = new HttpRequestMessage(HttpMethod.Post, url);
// Request Header
request.Headers.Add("Authorization", "Bearer " + accessToken);
var parameters = new Dictionary<string, string>()
{
{ "type", "text" },
{ "text", "Hello World" }
};
var parameters2 = new Dictionary<string, Dictionary<string, string>>()
{
{ "messages", parameters}
};
var str = #"{""messages"":"" {""type"": ""text"",""text"" : ""Hello World""}""}";
var content = new JObject(str);
request.Content = new StringContent(
content.ToString(),
Encoding.UTF8,
"application/json"
);
await client.SendAsync(request);
Of course it doesn't work
question⓵
How can I write the example In C#???
question⓶
If you can, could you provide entire procedure of Send broadcast message from scratch?
PS
For those who are worried, I'm still gathering answers in my first question and also trying to make it work.
I solved the problem.
The procedure is below.
To make a class following this link http://json2csharp.com/
To serialize that
3.
To useu ToString() to a serialized json
And the entire code is like this
// To creat HttpClient
var client = new HttpClient();
// Accesstoken
var accessToken = "my token";
// URL
var url = "https://api.line.me/v2/bot/message/broadcast";
// Post
var request = new HttpRequestMessage(HttpMethod.Post, url);
// Request Header
request.Headers.Add("Authorization", "Bearer " + accessToken);
// To create messages
var message1 = new Message("text", "Hello World1");
var message2 = new Message("text", "Hello World2");
var root = new RootObject();
root.addMessage(message1);
root.addMessage(message2);
// To serialize
var json = JsonConvert.SerializeObject(root);
request.Content = new StringContent(
json.ToString(),
Encoding.UTF8,
"application/json"
);
await client.SendAsync(request);

Issue Exchanging Authorization Code for Token Google Api

I have checked every thing repeatedly and does not seem to have any issue in code or logic.
Here is the code:
var content = new FormUrlEncodedContent(new Dictionary<string, string>
{
{"grant_type", "authorization_code"},
{"code", code},
{"redirect_uri", redirectUri.ToString()},
{"client_id", clientId},
{"client_secret", clientSecret}
});
string token = string.Empty;
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));
var response = client.PostAsync(tokenEndpoint, content);
var responseContent = response.Result.Content.ReadAsStringAsync();
token = responseContent.ToString();
if (!response.Result.IsSuccessStatusCode) ;
}
return token;
And i am getting error:
"error": "redirect_uri_mismatch",
"error_description": "Bad Request"
The Url of the above page is : http://localhost:62188/dashboard/googleSync.aspx
And in Google Console i have this Url as Authorized Return Url :
So what am i missing here?
Ok: had to use this : :redirect_uri = "postmessage" and it worked.

HttpClient post request for WebApi using asp.net mvc application

I'm trying to consume WebApi but I'm having issues. My 'IsSuccessStatusCode' is always false and I have 404 in response.
I have tried multiple methods but can't be able to do it correctly.
Constants:
const string baseUri = ""; // base url of API
const string setDealFlagUri = "Deals/SetDealFlag";
Method 1, using PostAsync:
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(baseUri);
var content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("deadId", "3"),
new KeyValuePair<string, string>("flagValueToSet", "true")
});
var response = await client.PostAsync(setDealFlagUri, content);
if (response.IsSuccessStatusCode)
{
return true;
}
}
Method 2, using PostAsJsonAsync:
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(baseUri);
DealFlag content = new DealFlag
{
deadId = 3,
flagValueToSet = true
};
var response = await client.PostAsJsonAsync(setDealFlagUri, content);
if (response.IsSuccessStatusCode)
{
return true;
}
}
WebApi request detail:
Curl:
curl -X POST --header 'Accept: application/json' '{baseApiurl}/Deals/SetDealFlag?dealId=3&flagValueToSet=true'
Request URL
{baseApiurl}/Deals/SetDealFlag?dealId=3&flagValueToSet=true
Response Body
{
"Successful": true,
"ErrorMessages": [],
"ValidationResults": {
"IsValid": false,
"ValidationErrors": []
}
}
Response Headers
{
"pragma": "no-cache",
"date": "Wed, 24 Aug 2016 18:38:01 GMT",
"content-encoding": "gzip",
"server": "Microsoft-IIS/8.0",
"x-aspnet-version": "4.0.30319",
"x-powered-by": "ASP.NET",
"vary": "Accept-Encoding",
"content-type": "application/json; charset=utf-8",
"cache-control": "no-cache",
"content-length": "198",
"expires": "-1"
}
Please help me to use this webapi function correctly.
Thanks!
I think that the problem is that your controller method has signature like
[HttpPost]
public HttpResponseMessage SetDealFlag(int dealId, bool flagValueToSet)
Am I right? If your answer is "Yes" so your method wants parameters in the URL.
And so you get 404 error becouse no one of yours Web API methods matches to that URL.
Send your parameters dealId and flagValueToSet in the URL is the solution.
I wrote simple console app for testing my theory and it works perfectly:
public static void Main(string[] args)
{
using (var client = new HttpClient())
{
try
{
// Next two lines are not required. You can comment or delete that lines without any regrets
const string baseUri = "{base-url}";
client.BaseAddress = new Uri(baseUri);
var content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("deadId", "3"),
new KeyValuePair<string, string>("flagValueToSet", "true")
});
// response.Result.IsSuccessStatusCode == true and no errors
var response = client.PostAsync($"{baseUri}/Deals/SetDealFlag?dealId=3&flagValueToSet=true", null);
// response.Result.IsSuccessStatusCode == false and 404 error
// var response = client.PostAsync($"{baseUri}/Deals/SetDealFlag", content);
response.Wait();
if (response.Result.IsSuccessStatusCode)
{
return;
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
throw;
}
}
}

Categories