I want to post a request to a url, using content-type and authorization. I am getting error 400 "Bad Request". I have tested with the same data and headers in python and it worked.
So I think there is something wrong with how I set up my headers. But I haven't found a workaround.
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net.Http.Headers;
using System.Net.Http;
namespace PostRequests
{
//var data={"bio":"cheesy"}
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private static readonly HttpClient client = new HttpClient();
private void go_Click(object sender, EventArgs e)
{
var values = new Dictionary<string, string>
{
{"bio", "test"}
};
sendPost("https://discord.com/api/v9/users/#me", values);
}
async void sendPost(string url, Dictionary<string, string> vals)
{
string authValue = "mytoken";
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(authValue);
var content = new FormUrlEncodedContent(vals);
var request = new HttpRequestMessage(new HttpMethod("PATCH"), url) { Content = content };
request.Headers.Accept.Clear();
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = await client.SendAsync(request);
}
}
}
Related
I am trying to get data from a IT ticketing system through API in SSIS using Script Component, very new to this:
I am just starting with 1 field called Supplier, for that i have so far written below scripts:
Script Component
Created a class called ResultAPI:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SC_b15eeeff0e3544d3a882578b3eb9bbba
{
public class ResultAPI
{
public string Supplier { get; set; }
}
}
Another class called GenericResponse:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SC_b15eeeff0e3544d3a882578b3eb9bbba
{
public class GenericResponse
{
public ResultAPI[] ListData { get; set; }
}
public class ResultGen
{
public GenericResponse Result { get; set; }
}
}
Main:
public override void CreateNewOutputRows()
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("https://***************");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
var cred = Convert.ToBase64String(Encoding.ASCII.GetBytes(string.Format("{0}:{1}", "username", "pwd")));
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", cred);
string APIUrl = string.Format("https://**************");
var response = client.GetAsync(APIUrl).Result;
if (response.IsSuccessStatusCode)
{
var result = response.Content.ReadAsStringAsync().Result;
var serializer = new JavaScriptSerializer();
var data = serializer.Deserialize<ResultAPI>(result);
APIResultsBuffer.AddRow();
//APIResultsBuffer.SupplierType = data.SupplierType;
APIResultsBuffer.Supplier = data.Supplier;
//APIResultsBuffer.nextpage = data.nextpage;
//APIResultsBuffer.previouspage = data.previouspage;
//APIResultsBuffer.recordcount = data.recordcount;
//APIResultsBuffer.HREF = data.HREF;
}
}
}
When I execute the package, i get the attached error:
Error
Not sure exactly where this error is.
Hoping to download this file in SQL Server table
I created a HttpSelfHostServer service hosting controller for communication in web API
problem is that I want the ability to view images
ex: http://localhost:8080/images/pic.jpg
but the self host doesn't allow me to do this
it use to be IAppBuilder.UseFileServer but it's different with HttpSelfHostServer
here's the server code
using Autofac;
using Autofac.Integration.WebApi;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Formatting;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Http.SelfHost;
namespace WebAPIServerV2
{
public class WebAPIServer
{
private HttpSelfHostServer m_Server;
private ILifetimeScope m_lifetimeScope;
public WebAPIServer(ILifetimeScope lifetimeScope)
{
m_lifetimeScope = lifetimeScope;
}
public void Start(string url)
{
if (m_Server != null)
{
Stop();
}
var config = new HttpSelfHostConfiguration(url);
config.DependencyResolver = new AutofacWebApiDependencyResolver(m_lifetimeScope);
config.MaxReceivedMessageSize = int.MaxValue;
config.Routes.MapHttpRoute(
name: "ServerAPI",
routeTemplate: "server/{controller}/{action}"
);
config.Formatters.Clear();
config.Formatters.Add(new JsonMediaTypeFormatter());
config.Formatters.JsonFormatter.SerializerSettings.Converters.Add(new StringEnumConverter());
config.Formatters.JsonFormatter.SerializerSettings =
new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
};
m_Server = new HttpSelfHostServer(config);
m_Server.OpenAsync().Wait();
if (Environment.UserInteractive)
Console.WriteLine($"WebAPI server start at:{url}");
}
public void Stop()
{
m_Server?.Dispose();
m_Server = null;
}
}
}
well I found it!
https://social.msdn.microsoft.com/Forums/en-US/ed7e5248-69e2-4644-aa02-8da7d13c9765/hosting-a-file-with-httpselfhostserverhttpselfhostconfiguration?forum=aspwebapi
using System;
using System.IO;
using System.Net.Http;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
namespace WebAPIServer
{
internal class StaticFileHandler : DelegatingHandler
{
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
if (request.RequestUri.AbsolutePath.StartsWith("/server/"))
return base.SendAsync(request, cancellationToken);
var path = Environment.CurrentDirectory;
var newUri = new Uri(path);
var newPath = newUri.AbsolutePath + request.RequestUri.AbsolutePath;
newUri = new Uri(newPath);
if (!File.Exists(newUri.LocalPath))
{
return base.SendAsync(request, cancellationToken);
}
else
{
return Task<HttpResponseMessage>.Factory.StartNew(() =>
{
var response = request.CreateResponse();
response.Content = new StreamContent(new FileStream(newUri.LocalPath, FileMode.Open));
return response;
});
}
}
}
}
ofcourse server is the prefix for the API so it was easy
Hi im so sorry for the generic question i am really new to C#. I am using a previous colleagues code but im looking to populate a textbox on a form with the data from a class.
This is the code for the thing i want to reference
public string GetToken(string username, string password) {
var request = SvcRequest
.Get(_url)
.WithAuthentication(this.CreateHeader(username, password))
.ReturningXml();
var response = _svc.Send(request);
return this.ExtractToken(response.Body);
I need to populate my text box with this.ExtractToken(response.Body). How do i do this?
Thanks a lot!
Code for main .cs file
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.XPath;
using System.Configuration;
using System.IO;
namespace EbsWebServices
{
internal sealed class EbsAuthManager
{
private readonly string _url;
private readonly SvcUtility _svc = new SvcUtility();
public EbsAuthManager()
{
_url = "URL_HERE";
if(!_url.EndsWith("/"))
{
_url += "/";
}
_url += "Rest/Authentication";
}
public string GetToken(string username, string password)
{
var request = SvcRequest
.Get(_url)
.WithAuthentication(this.CreateHeader(username, password))
.ReturningXml();
var response = _svc.Send(request);
return this.ExtractToken(response.Body);
}
private string CreateHeader(string username, string password)
{
var credentials = String.Format("{0}:{1}", username, password);
var encoded = Convert.ToBase64String(Encoding.UTF8.GetBytes(credentials));
return String.Format("Basic {0}", encoded);
}
private string ExtractToken (string xml)
{
var doc = new XmlDocument();
doc.LoadXml(xml);
var navigator = doc.DocumentElement.CreateNavigator();
var success = navigator
.SelectChildren("Success", string.Empty)
.Cast<XPathNavigator>()
.First();
var token = navigator
.SelectChildren("Token", string.Empty)
.Cast<XPathNavigator>()
.First();
return Convert.ToBoolean(success.InnerXml)
? token.InnerXml
: null;
}
}
}
Code for my form
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using EbsWebServices;
namespace EBSGetTokenForm
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
}
}
}
Hi i have a Api that i want to use to collect data from a backend that spits out json i need to get this via C# Application and it's http functionalities. My question is should i use a rest api and setup an async thread that downloads the data and then use the data as i want to from there or should i somehow use something close to a Web Api i have an authentication that is required to exist in a header. This has given me some hedaches because i keep on being split by what to use for what. I mean i need to do a Httprequest with a header. this i later on need to use for posting to another database. but the user of the program should not have to see the data itself. i have two examples that i have done but i don't know with what i should continue? this is my two examples in code...
Example 1
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.IO;
namespace Plugin
{
public enum HttpVerb
{
GET,
POST,
PUT,
DELETE
}
class Api
{
private HttpVerb HttpMethod { get; set; }
public Api()
{}
public string startDownload()
{
return (Download("sending token"));
}
private string Download(string token)
{
string strResponseValue = string.Empty;
string finnishedOutput = string.Empty;
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("Url");
request.Headers.Add("Authorization", "Bearer " + token);
request.Method = HttpMethod.ToString();
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
Stream responseStream = response.GetResponseStream();
StreamReader reader = new StreamReader(responseStream);
strResponseValue = reader.ReadToEnd();
}
return strResponseValue;
}
catch (WebException e)
{
HttpWebResponse httpResponse = (HttpWebResponse)e.Response;
if ((int)httpResponse.StatusCode == 401)
{}
int errorCodeInt;
string errorCode;
errorCodeInt = (int)httpResponse.StatusCode;
errorCode = errorCodeInt.ToString();
return errorCode;
}
}
}
}
Example 2
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace TestAPi
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
Api.InitializeClient("");
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using System.Net.Http;
namespace TestAPi
{
public class Api
{
private static HttpClient ApiClient { get; set;}
private string url { get; set;}
public static void InitializeClient(string token)
{
ApiClient = new HttpClient();
ApiClient.BaseAddress = new Uri("your url");
ApiClient.DefaultRequestHeaders.Accept.Clear();
ApiClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
ApiClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("Bearer Authentication"));
}
public async Task<Data> LoadData()
{
url = ApiClient.BaseAddress.ToString();
using (HttpResponseMessage response = await ApiClient.GetAsync(url))
{
if (response.IsSuccessStatusCode)
{
Data data = await response.Content.ReadAsAsync<data>();
return data;
}
else
{
throw new Exception(response.ReasonPhrase);
}
}
}
}
}
I am trying to post a message on the #general channel and this worked when was doing it through a console app but Now I am using MVC and the message doesn't seem to get posted. Also, earlier I was using the webhook URL and now I am using the access token that I have.
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
namespace SlackClient.Controllers
{
public class SlackClient
{
private readonly Uri _uri;
private readonly Encoding _encoding = new UTF8Encoding();
public SlackClient(string urlWithAccessToken)
{
_uri = new Uri(urlWithAccessToken);
}
//Post a message using simple strings
public void PostMessage(string text, string username = null, string channel = null)
{
Payload payload = new Payload()
{
Channel = channel,
Username = username,
Text = text
};
PostMessage(payload);
}
//Post a message using a Payload object
public void PostMessage(Payload payload)
{
string payloadJson = JsonConvert.SerializeObject(payload);
using (WebClient client = new WebClient())
{
NameValueCollection data = new NameValueCollection();
data["payload"] = payloadJson;
var response = client.UploadValues(_uri, "POST", data);
//The response text is usually "ok"
string responseText = _encoding.GetString(response);
}
}
}
//This class serializes into the Json payload required by Slack Incoming WebHooks
public class Payload
{
[JsonProperty("channel")]
public string Channel { get; set; }
[JsonProperty("username")]
public string Username { get; set; }
[JsonProperty("text")]
public string Text { get; set; }
}
}
And the other class is SlackClientTest.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace SlackClient.Controllers
{
public class SlackClientTest
{
void TestPostMessage()
{
string urlWithAccessToken = "https://srishti2604.slack.com/services/hooks/incoming-webhook?token=my-tokenHere.";
SlackClient client = new SlackClient(urlWithAccessToken);
client.PostMessage(username: "Mr. Torgue",
text: "THIS IS A TEST MESSAGE! SQUEEDLYBAMBLYFEEDLYMEEDLYMOWWWWWWWW!",
channel: "#general");
}
}
}
Could someone tell me what might me wrong?
My console app looks like this
SlackClient.cs
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
namespace SlackProject1
{
public class SlackCient
{
private readonly Uri _webhookUrl;
private readonly HttpClient _httpClient = new HttpClient();
public SlackCient(Uri webhookUrl)
{
_webhookUrl = webhookUrl;
}
public async Task<HttpResponseMessage> SendMessageAsync(string message,
string channel = null, string username = null)
{
var payload = new
{
text = message,
channel,
username,
};
var serializedPayload = JsonConvert.SerializeObject(payload);
var response = await _httpClient.PostAsync(_webhookUrl,
new StringContent(serializedPayload, Encoding.UTF8, "application/json"));
return response;
}
}
}
And the Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SlackProject1
{
class Program
{
static void Main(string[] args)
{
Task.WaitAll(IntegrateWithSlackAsync());
}
private static async Task IntegrateWithSlackAsync()
{
var webhookUrl = new Uri("https://hooks.slack.com/services/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");
var slackClient = new SlackCient(webhookUrl);
while (true)
{
Console.Write("Type a message: ");
var message = Console.ReadLine();
var response = await slackClient.SendMessageAsync(message);
var isValid = response.IsSuccessStatusCode ? "valid" : "invalid";
Console.WriteLine($"Received {isValid} response.");
}
}
}
}