C# How to post data with multiple POST requests through Facebook API - c#

I've been trying to post a message along with a link, I can send one POST request, but I am not sure how would one send two.
Here's my code:
private void Button2_Click(object sender, EventArgs e)
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("https://graph.facebook.com");
string message = "hello";
string link = "www.facebook.com"
var payload = GetPayload(new {message});
HttpResponseMessage response2 = client.PostAsync($"me/feed?access_token={TextBox1.Text}", payload).Result;
}
}
private static StringContent GetPayload(object data)
{
var json = JsonConvert.SerializeObject(data);
return new StringContent(json, Encoding.UTF8, "application/json");
}
I am not sure how can I include the link too along with the message.

Al-right it turns out that the variable link should be passed as such:
var data = {message, link}
Thanks to chetan.

Related

HttpClient.PostAsync causes infinite Loop when calling at Page_Load

I have this Web Api call in my code behind. This is for my Single-Sign-On using Windows credential from our AD. What it did is just call the Web Api and check if the User is Authenticated and have access to the App.
I successfully call my Web Api using HttpClient.PostAsync but I'm wondering why it called several times in my Page_Load?
Please see below my Page_Load how I call the Web Api:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
var languages = Language.Enabled().OrderByDescending(x => x.IsDefault);
var selected = languages.Where(x => x.Code == HSESA.Library.Helpers.Context.PublicLanguage().Code).Select(x => x.Code).FirstOrDefault();
Test();
}
}
And here is the Test() method and how I initialized HttpClient:
private static HttpClient client = new HttpClient();
protected void Test()
{
string user = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
string FromUrl = HttpContext.Current.Request.Url.AbsoluteUri;
#region Old Code
var postData = new List<KeyValuePair<string, string>>();
postData.Add(new KeyValuePair<string, string>("Login", user));
postData.Add(new KeyValuePair<string, string>("FromUrl", FromUrl));
System.Net.Http.HttpContent content = new System.Net.Http.FormUrlEncodedContent(postData);
string url = "http://localhost:1899";
client.BaseAddress = new Uri(url);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
var response = client.PostAsync("/api/login/checkLogin", content).Result;
if (response.IsSuccessStatusCode)
{
LoginItemViewModel data = null;
string responseString = response.Content.ReadAsStringAsync().Result;
Newtonsoft.Json.Linq.JObject json = Newtonsoft.Json.Linq.JObject.Parse(responseString);
data = Newtonsoft.Json.JsonConvert.DeserializeObject<LoginItemViewModel>(responseString);
}
#endregion
}
Thanks in advance to someone that can help me with my problem.

Xamarin Forms Post Request Http Issue

I'm working on making a POST request using my Xamarin form to send data to an Action in my controller in my WebAPI project. The code with breakpoints doesn't go beyond
client.BaseAddress = new Uri("192.168.79.119:10000");
I have namespace System.Net.Http and using System mentioned in the code.
private void BtnSubmitClicked(object sender, EventArgs eventArgs)
{
System.Threading.Tasks.Task<HttpResponseMessage> statCode = ResetPassword();
App.Log(string.Format("Status Code", statCode));
}
public async Task<HttpResponseMessage> ResetPassword()
{
ForgotPassword model = new ForgotPassword();
model.Email = Email.Text;
var client = new HttpClient();
client.BaseAddress = new Uri("192.168.79.119:10000");
var content = new StringContent(
JsonConvert.SerializeObject(new { Email = Email.Text }));
HttpResponseMessage response = await client.PostAsync("/api/api/Account/PasswordReset", content); //the Address is correct
return response;
}
Need a way to make a Post request to that Action and sending that String or the Model.Email as a parameter.
You need to use a proper Uri and also await the Task being returned from the called method.
private async void BtnSubmitClicked(object sender, EventArgs eventArgs) {
HttpResponseMessage response = await ResetPasswordAsync();
App.Log(string.Format("Status Code: {0}", response.StatusCode));
}
public Task<HttpResponseMessage> ResetPasswordAsync() {
var model = new ForgotPassword() {
Email = Email.Text
};
var client = new HttpClient();
client.BaseAddress = new Uri("http://192.168.79.119:10000");
var json = JsonConvert.SerializeObject(model);
var content = new StringContent(json, System.Text.Encoding.UTF8, "application/json");
var path = "api/api/Account/PasswordReset";
return client.PostAsync(path, content); //the Address is correct
}

Simplest way to call REST

I have call to REST service from jscript that works fine:
post('/MySite/myFunct', { ID:22 })
How to make this call from C# in most native c# way?
UPD:
I need HTTPS solution also.
UPD:
And I need to use cookies
HttpClient client = new HttpClient();
var values = new Dictionary<string, string>
{
{ "ID", "22" }
};
var content = new FormUrlEncodedContent(values);
var response = await client.PostAsync("http://www.example.com", content);
var responseString = await response.Content.ReadAsStringAsync();
Old traditional way is using HttpClient / HttpWebRequest.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost/api/Test/TestPostData");
request.Method = "POST";
SampleModel model = new SampleModel();
model.PostData = "Test";
request.ContentType = "application/json";
JavaScriptSerializer serializer = new JavaScriptSerializer();
using (var sw = new StreamWriter(request.GetRequestStream()))
{
string json = serializer.Serialize(model);
sw.Write(json);
sw.Flush();
}
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Apart from this I prefer more Restclient /Restsharp from nuget.
A simple example of post request will be like this
using RestSharp;
using RestTest.Model;
private void button1_Click(object sender, EventArgs e)
{
var client = new RestClient();
var request = new RestRequest();
request.BaseUrl = "http://carma.org";
request.Action = "api/1.1/searchPlants";
request.AddParameter("location", 4338);
request.AddParameter("limit", 10);
request.AddParameter("color", "red");
request.AddParameter("format", "xml");
request.ResponseFormat = ResponseFormat.Xml;
var plants = client.Execute<PowerPlantsDTO>(request);
MessageBox.Show(plants.Count.ToString());
}
You can use HTTP Verbs directly from call
A Post example:
public void Create(Product product)
{
var request = new RestRequest("Products", Method.POST); < ----- Use Method.PUT for update
request.AddJsonBody(product);
client.Execute(request);
}
A Delete Example
public void Delete(int id)
{
var request = new RestRequest("Products/" + id, Method.DELETE);
client.Execute(request);
}
For adding header in request
request.AddHeader("data", "test");
A Get Request
private RestClient client = new RestClient("http://localhost:8080/api/");
RestRequest request = new RestRequest("Products", Method.GET);
RestResponse<YourDataModel> response = client.Execute<YourDataModel>(request);
var name = response.Data.Name;

Calling ASP.NET WebAPI using HttpClient

I am trying to grab some values from my web api using HttpClient. I managed to get a true status. However, I do not know how to grab values/read the JSON document. May I know if there's a way to do it?
I am currently doing in Xamarin.Forms in Visual Studio.
This is my code.
When I enter this URL into my browser, the document reads like this
{"d":[{"__type":"Info:#website.Model","infoClosingHours":"06:00:00 PM","infoID":1,"infoOpeningDays":"Monday","infoOpeningHours":"09:00:00 AM","infoStatus":"Open"}]}
xaml file
<Button Text="Grab Value" Clicked="GetData"/>
xaml.cs file
private void GetData(object sender, EventArgs e)
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("ipaddress");
// Add an Accept header for JSON format.
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
try{
HttpResponseMessage response = client.GetAsync("WebServices/information.svc/GetInformationJSON").Result;
HttpResponseMessage response1 = client.GetAsync("WebServices/information.svc/GetInformationJSON").Result;
}
catch
{
}
}
I recommend using a static HttpClient if you will have any kind of decent load on your app. Otherwise, you can experience port exhaustion and bring the server to its knees. See my response on using instance-based vs. static HttpClients - What is the overhead of creating a new HttpClient per call in a WebAPI client?
You could use it like this:
private async void GetData(object sender, EventArgs e)
{
using (HttpClient client = new HttpClient())
{
client.BaseAddress = new Uri("ipaddress");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
try
{
HttpResponseMessage response = client.GetAsync("WebServices/information.svc/GetInformationJSON").Result;
if (response.IsSuccessStatusCode)
{
MyObject responseObject = response.Content.ReadAsAsync<MyObject>();
}
}
catch
{
}
}
}
For this to work you need to create a class "MyObject" that has the Properties from your JSON-Data.
It would also be possible to just deserialize it to a dynamic object like this:
private async void GetData(object sender, EventArgs e)
{
using (HttpClient client = new HttpClient())
{
client.BaseAddress = new Uri("ipaddress");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
try
{
HttpResponseMessage response = client.GetAsync("WebServices/information.svc/GetInformationJSON").Result;
if (response.IsSuccessStatusCode)
{
string jsonString = await response.Content.ReadAsStringAsync();
dynamic dynamicObject = JsonConvert.DeserializeObject(jsonString);
}
}
catch
{
}
}
}
For this you would need the Newtonsoft.Json.

Trying to Post a Slack Message through NameValueCollection using HttpClient.PostAsync instead of WebClient

I am trying to use HttpClient to post a NameValueCollection to a specific Url. I have the code working using WebClient, but I'm trying to figure out if it is possible to do using HttpClient.
Below, you will find my working code that uses WebClient:
var payloadJson = JsonConvert.SerializeObject(new { channel, username, text });
using (var client = new WebClient())
{
var data = new NameValueCollection();
data["payload"] = payloadJson;
var response = client.UploadValues(_uri, "POST", data);
var responseText = _encoding.GetString(response);
}
I'm using this code to try to post a message to a Slack Channel using a web integration. Is there a way to implement this same functionality while using HttpClient?
The Slack error that I receive when I try to use HttpClient is "missing_text_or_fallback_or_attachment".
Thanks in advance for any help!
Using HttpClient
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://yourdomain.com/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var data = new NameValueCollection();
data["payload"] = payloadJson;
StringContent content = new StringContent(JsonConvert.SerializeObject(data), Encoding.UTF8, "application/json");
try
{
HttpResponseMessage response = await client.PostAsync("api/yourcontroller", content);
if (response.IsSuccessStatusCode)
{
//MessageBox.Show("Upload Successful", "Success", MessageBoxButtons.OK);
}
}
catch (Exception)
{
// ignored
}
}
While you are tagging #slack in the question, I suggest you to use Slack.Webhooks nuget package.
Example usage I found is in here;
https://volkanpaksoy.com/archive/2017/04/11/Integrating-c-applications-with-slack/
var url = "{Webhook URL created in Step 2}";
var slackClient = new SlackClient(url);
var slackMessage = new SlackMessage
{
Channel = "#general",
Text = "New message coming in!",
IconEmoji = Emoji.CreditCard,
Username = "any-name-would-do"
};
slackClient.Post(slackMessage);

Categories