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);
Related
I am using Botframework adaptive dialog template (c#). I already obtained a token from a HttpRequest and saved it as a conversation state property conversation.token, now I am trying to use this token to make another API call with HttpRequest. But from the official document of HttpRequest Class, it seems there is no options to add the authentication token. I tried to add the token in the Headers, but did not work, it showed 401 Unauthorized error. How should the authorization be handled in HttpRequest in adaptive dialog?
new HttpRequest()
{
Url = "http://example.com/json",
ResultProperty = "conversation.httpResponse",
Method = HttpRequest.HttpMethod.GET,
ResponseType = HttpRequest.ResponseTypes.Json,
Headers = new Dictionary<string, AdaptiveExpressions.Properties.StringExpression>()
{
{"Authorization", "Bearer ${conversation.token.content.token}"},
},
},
new SendActivity("${conversation.httpResponse}"),
Instead of using HttpRequest, I made the API call inside CodeAction with custom code.
First make a POST request to get the token, then make a GET request to call the main API. In the GET request, the authorization can be added in this way: client.DefaultRequestHeaders.Add("Authorization", "Bearer " + accessToken);.
new CodeAction(async (dc, options) =>
{
var my_jsondata = new
{
Username = "username",
Password = "password"
};
var json = JsonConvert.SerializeObject(my_jsondata);
var data = new StringContent(json, Encoding.UTF8, "application/json");
var Tokenurl = "https://example.com/token?HTTP/1.1";
using var Tokenclient = new HttpClient();
var Tokenresponse = await Tokenclient.PostAsync(Tokenurl, data);
string Toeknresult = Tokenresponse.Content.ReadAsStringAsync().Result;
var Tokenjo = JObject.Parse(Tokenresult);
using var client = new HttpClient();
var url = "https://example.com/mainapi?HTTP/1.1";
var accessToken = Tokenjo["token"];
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + accessToken);
var response = await client.GetAsync(url);
string result = response.Content.ReadAsStringAsync().Result;
dc.State.SetValue("conversation.httpresponse", response);
dc.State.SetValue("conversation.result", result);
return await dc.EndDialogAsync();
}),
I'm trying to make a simple request to the Basecamp API, I'm following the instructions provided adding in a sample user agent and my credentials yet I keep getting a 403 Forbidden response back.
My credentials are definitely correct so is it a case of my request/credentials being set incorrectly?
This is what I have (removed personal info):
var httpClient = new HttpClient();
var content = new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>("User-Agent", "MyApp [EMAIL ADDRESS]") });
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(string.Format("{0}:{1}", "[USERNAME]", "[PASSWORD]"))));
var response = await httpClient.PostAsync("https://basecamp.com/[USER ID]/api/v1/projects.json", content);
var responseContent = response.Content;
using (var reader = new StreamReader(await responseContent.ReadAsStreamAsync()))
{
Console.WriteLine(await reader.ReadToEndAsync());
}
A quick look over their documentation seems to indicate that the projects.json endpoint accepts the following in the body of the POST:
{
"name": "This is my new project!",
"description": "It's going to run real smooth"
}
You're sending the User-Agent as the POST body. I'd suggest you change your code as follows:
var credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes(string.Format("{0}:{1}", "[USERNAME]", "[PASSWORD]")));
using (var httpClient = new HttpClient())
{
httpClient.DefaultRequestHeaders.Add("User-Agent", "MyApp [EMAIL ADDRESS]");
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", credentials);
var response = await httpClient.PostAsJsonAsync(
"https://basecamp.com/[USER ID]/api/v1/projects.json",
new {
name = "My Project",
description = "My Project Description"
});
var responseContent = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseContent);
}
This posts the payload as specified in the docs and sets your user agent in the headers as it should be.
I am trying to add a worklog for a issue in JIRA Software, but I just receive a Bad Request.
Does anyone know what could be the problem?
var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders
.Authorization = new AuthenticationHeaderValue(
"Basic",
Convert.ToBase64String(
convertStringtoByteArray(
userName,
userPassword)));
var json = Newtonsoft.Json.JsonConvert.SerializeObject(
new
{
comment = "I did some work here.",
started = "2017-08-17T10:52:10.475+0000",
timeSpentSeconds = 12000
};
var content = new StringContent(json, Encoding.UTF8, "application/json");
var apiUrl = "https://<ACCOUNT>.atlassian.net/rest/api/2/issue/{KEY}/worklog"
var result = httpClient .PostAsync(apiUrl, content).Result;
Thanks in advance!
Possibly your instance requires the visibility fields also.
As per the Jira Rest API docs
sample request is:
{
"comment": "I did some work here.",
"visibility": {
"type": "group",
"value": "jira-developers"
},
"started": "2017-07-31T14:11:53.507+0000",
"timeSpentSeconds": 12000
}
Can you add the visibility values and check ?
The string conversion is the issue, please try like this
Prepare work log object using JObject
JObject workLogObject = new JObject(
new JProperty("comment", jiraText),
new JProperty("started", strDate),
new JProperty("timeSpentSeconds", seconds));
Create string with format option
var workLogData = workLog.ToString(Newtonsoft.Json.Formatting.Indented);
var content = new StringContent(workLogData, Encoding.UTF8, "application/json");
Pass content
var result = httpClient .PostAsync(apiUrl, content).Result;
I have asp.net mvc5 project that I want to call another API using JSON,
and I want to call that API from my Controller action because I need to do some hashing in there,
It's my first time doing this, and I need to send the request in JSON and also get responses in JSON all of that using the controller action.
If your method is POST :
string uri = "yourdomain/api/controller/method;
var client = new HttpClient();
var values = new Dictionary<string, string>()
{
{"username", SecurityHelper.EncryptQueryString(username)},
{"password", SecurityHelper.EncryptQueryString(password)},
};
var content = new FormUrlEncodedContent(values);
var response = await client.PostAsync(uri, content);
response.EnsureSuccessStatusCode();
If your method is GET :
string url = "domain/api/controller/method?parameter1=param";
using (var client = new HttpClient())
{
HttpResponseMessage response = await client.GetAsync(url).ConfigureAwait(false);
if (response.IsSuccessStatusCode)
{
var jsonResponse = response.Content.ReadAsStringAsync().Result;
bool data = JsonConvert.DeserializeObject<bool>(jsonResponse);
return data;
}
}
var client = new HttpClient();
var payload = #"{
'CPU': 'Intel',
'PSU': '500W',
'Drives': [
'DVD read/writer',
'500 gigabyte hard drive',
'200 gigabype hard drive'
]
}";
var content = new StringContent(payload, Encoding.UTF8, "application/json");
var url = {APIEndpoint};
var result = await client.PostAsync(url, content);
Response parsing using JSON.NET:
JObject joResponse = JObject.Parse(result);
I'm trying to make a simple request to the Basecamp API, I'm following the instructions provided adding in a sample user agent and my credentials yet I keep getting a 403 Forbidden response back.
My credentials are definitely correct so is it a case of my request/credentials being set incorrectly?
This is what I have (removed personal info):
var httpClient = new HttpClient();
var content = new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>("User-Agent", "MyApp [EMAIL ADDRESS]") });
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(string.Format("{0}:{1}", "[USERNAME]", "[PASSWORD]"))));
var response = await httpClient.PostAsync("https://basecamp.com/[USER ID]/api/v1/projects.json", content);
var responseContent = response.Content;
using (var reader = new StreamReader(await responseContent.ReadAsStreamAsync()))
{
Console.WriteLine(await reader.ReadToEndAsync());
}
A quick look over their documentation seems to indicate that the projects.json endpoint accepts the following in the body of the POST:
{
"name": "This is my new project!",
"description": "It's going to run real smooth"
}
You're sending the User-Agent as the POST body. I'd suggest you change your code as follows:
var credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes(string.Format("{0}:{1}", "[USERNAME]", "[PASSWORD]")));
using (var httpClient = new HttpClient())
{
httpClient.DefaultRequestHeaders.Add("User-Agent", "MyApp [EMAIL ADDRESS]");
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", credentials);
var response = await httpClient.PostAsJsonAsync(
"https://basecamp.com/[USER ID]/api/v1/projects.json",
new {
name = "My Project",
description = "My Project Description"
});
var responseContent = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseContent);
}
This posts the payload as specified in the docs and sets your user agent in the headers as it should be.