How to set up a Windows.Web.Http.HttpClient PostAsync with basic authorization++ - httpclient

How to set up a Windows.Web.Http.HttpClient PostAsync with basic authorization and mediatype in addition to key/value pairs in Json?
I cannot find any good documentation or examples on how to do this.
These official sites offer very little documentation on how to solve this:
https://msdn.microsoft.com/en-us/library/windows/apps/xaml/windows.web.http.httpclient.aspx
Help appreciated! Thanks!

I found an solution that worked for me:
Dictionary<string, string> pairs = new Dictionary<string, string>();
pairs.Add("client_id", Constants.CLIENT_ID);
pairs.Add("grant_type", "authorization_code");
pairs.Add("code", code);
var formContent = new HttpFormUrlEncodedContent(pairs);
var base64Creds = Convert.ToBase64String(System.Text.UTF8Encoding.UTF8.GetBytes(string.Format("{0}:{1}", Constants.CLIENT_ID, Constants.CLIENT_SECRET)));
var httpFilter = new Windows.Web.Http.Filters.HttpBaseProtocolFilter();
httpFilter.CacheControl.ReadBehavior = Windows.Web.Http.Filters.HttpCacheReadBehavior.MostRecent;
var client = new HttpClient(httpFilter);
client.DefaultRequestHeaders.Authorization = new HttpCredentialsHeaderValue("Basic", base64Creds);
HttpResponseMessage response = await client.PostAsync(new Uri(Constants.GET_TOKEN_URL), formContent);
client.Dispose();

You can try something like this
HttpClient client = new HttpClient();
string jsonContent = JsonConvert.SerializeObject(YourObject);
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", AuthenticationTokenString);
StringContent theContent = new StringContent(jsonContent, System.Text.Encoding.UTF8, "application/json");
HttpResponseMessage aResponse = await client.PostAsync(new Uri(UrlValue), theContent);
string responseContent = await aResponse.Content.ReadAsStringAsync();
client.Dispose();
Edit : The above code is using System.Net.Http.HttpClient
But if you would like to use Windows.Web.Http.HttpClient check out this link

Related

Update wiki page of tfs by calling rest-api

I want to update an already existing wiki page of tfs by using this document:
https://learn.microsoft.com/de-de/rest/api/azure/devops/wiki/pages/create%20or%20update?view=azure-devops-rest-4.1
Creating a new wiki-page (with content) is no problem. That is working fine.
But I want to edit an existing one. The tfs-documentation says that the only difference in API call is to use an "If-Match"-header (see section Request Header).
Here I have 3 situations:
Using no "If-Match"-Header or an empty: Get a "412 Precondition Failed" error.
Using a "If-Match"-Header with random value: Get a "400 Bad Request" error.
Using a "If-Match"-Header with exactly 40 characters (like the version-hash of the page-revision (e.g. '09f62be600a3b6d36d21b294dbb00921a5ba03ec')): Again "412 Precondition Failed" error.
I think the revision-hash (40 characters) should be a good way because the error message on non-40-chars returns the 400-error.
But it did not work? Has anyone an idea which id tfs is wanting? I used Postman and C# to update by API. Below you can see my example code:
var handler = new HttpClientHandler()
{
UseDefaultCredentials = true,
UseProxy = false,
};
var client = new HttpClient(handler);
client.BaseAddress = new Uri(".../pages/pagename" + "?api-version=4.1");
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
var putContent = new StringContent("{ \"content\": \"New content for page\" }", Encoding.UTF8, "application/json");
client.DefaultRequestHeaders.TryAddWithoutValidation("If-Match", "09f62be600a3b6d36d21b294dbb00921a5ba03ec");
var responseTask = client.PutAsync(client.BaseAddress, putContent);
var result = responseTask.Result;
var content = result.Content.ReadAsStringAsync().Result;
var code = result.StatusCode;
var body = content;
According to the Create or Update Wiki API, if we want to edit the wiki page,If-Match header is required. The value of If-Matchth is the wiki page ETag.
ETags can also be used for optimistic concurrency control, as a way to help prevent simultaneous updates of a resource from overwriting each other
so we need to get the wiki Etag before update. Please have a try to change the code as following:
var baseUrl = "xxxxx";
var handler = new HttpClientHandler()
{
UseDefaultCredentials = true,
UseProxy = false,
};
var client = new HttpClient(handler)
{
BaseAddress = new Uri(baseUrl)
};
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", "YourToken");
var getResult = client.GetAsync(baseUrl).Result;
var etag = getResult.Headers.GetValues("ETag");
var putContent = new StringContent("{ \"content\": \"New content for page\" }", Encoding.UTF8, "application/json");
client.DefaultRequestHeaders.TryAddWithoutValidation("If-Match", etag);
var responseTask = client.PutAsync(client.BaseAddress, putContent);
var result = responseTask.Result;
var content = result.Content.ReadAsStringAsync().Result;
Test Result:

How can I embed an inline image to Mailgun in ASP.net Core app?

I am trying to send an inline attached image with an email using Mailgun API but I don't know how could I solve it. Waht I know that I could somehow put something to the form but have not a a clue what. The raw image content? I suspect I also should change the content encoding to multipart form encoding.
Unfortunately, I couldn't find any example in the net.
Could someone help me please?
Thanks in advance.
Gabriel
var client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(UTF8Encoding.UTF8.GetBytes("api:" + API_KEY)));
var form = new Dictionary<string, string>();
form["from"] = FROM;
form["to"] = string.IsNullOrEmpty(name) ? email : name + "<" + email + ">";
form["subject"] = subject;
form["html"] = message;
HttpResponseMessage response = await client.PostAsync("https://api.mailgun.net/v2/" + DOMAIN + "/messages", new FormUrlEncodedContent(form));
I could manage to solve it in this way:
var client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(UTF8Encoding.UTF8.GetBytes("api:" + API_KEY)));
var content = new MultipartFormDataContent();
content.Add(new StringContent(FROM), "from");
content.Add(new StringContent(string.IsNullOrEmpty(name) ? email : name + "<" + email + ">"), "to");
content.Add(new StringContent(subject), "subject");
content.Add(new StringContent(message), "html");
var fileStream = new StreamContent(File.Open("./wwwroot/images/emaillogo.png", FileMode.Open, FileAccess.Read));
content.Add(fileStream, "inline", "logo.png");
HttpResponseMessage response = await client.PostAsync("https://api.mailgun.net/v2/" + DOMAIN + "/messages", content);

making a REST calls from unity3d - Need to pass JSON object using HTTPWebRequest

How to make a REST call in unity3d? especially POST method. I have tried with GET request. Pls see the below get request. so i need to write POST request in Unity3d. The post rquest should be in JSON format. I tried with below code. It's hit the my service but the receiving JSON object is null. Hope your support.
var httpWebReq = WebRequest.Create("http://localhost:6091/UserService.svc/RegisterUser/") as HttpWebRequest;
httpWebReq.ContentType = "text/json;charset=utf-8";
httpWebReq.Method= "POST";
using(var streamWriter = new StreamWriter(httpWebReq.GetRequestStream()))
{
string user = "{UserID:0," +
"Email:'ruwan#gmail.com'," +
"Password:'ruwan123'," +
"NickName:'ruwa'," +
"Age:35" +
"}";
byte[] formData = UTF8Encoding.UTF8.GetBytes(user);
httpWebReq.ContentLength = formData.Length;
streamWriter.Write(formData);
}
var httpResponse = (HttpWebResponse)httpWebReq.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var responseText = streamReader.ReadToEnd();
//Now you have your response.
//or false depending on information in the response
Debug.Log(responseText);
}
use WWW for GET,
use WWW with WWWForm for POST.
Finally i got the solution thanks to all for help.
Actually the easiest way to make rest call for WCF is we have to add the Newtonsoft.Json. Finally my code is-
GET --
WebClient myWebClient = new WebClient();
myWebClient.Encoding = Encoding.UTF8;
myWebClient.Headers.Add("Content-Type", "text/json");
var json = JsonConvert.DeserializeObject<Room[] >(new WebClient().DownloadString("Your URL"));
List<yourclass> test1= new List<yourclass>();
foreach (var test in json)
{
test1.Add(new yourclass()
{
yourclass.property1 = test.property1
});
}
Debug.Log(test1);
POST---
WebClient myWebClient = new WebClient();
var Test = JsonConvert.SerializeObject(new
{
YourProperty= 0
}, new JsonSerializerSettings() { Formatting = Newtonsoft.Json.Formatting.None });
myWebClient.Encoding = Encoding.UTF8;
myWebClient.Headers.Add("Content-Type", "text/json");
string responsebody = myWebClient.UploadString("Your URL", "POST", Test );
//if(responsebody == true)
Debug.Log(responsebody);

Azure REST WebClient PUT Blob

I'm trying to simply upload a new blob to an Azure Storage countainer using WebClient like this :
var sas = "[a new generated sas with Read, Write, List & Delete permissions]";
var sData = "This is a test!";
var sEndPoint = "http://myaccount.blob.core.windows.net/mycontainer/MyTest.txt" + sas;
var clt = new WebClient();
var res = await clt.UploadStringTaskAsync(sEndPoint, "PUT", sData);
This is giving me a "(400) Bad Request." error. Am I doing anything wrong here?
Thanks
(By the way, I need to use REST instead of Client API since I'm in a Silverlight project)
You would need to define a request header (x-ms-blob-type) for blob type and set it's value to BlockBlob. Also for Put requests you would need to define the Content-Length request header as well. I wrote a blog post on Shared Access Signatures and performing some blob operations using that (with both REST API and Storage Client library) which you can read here: http://gauravmantri.com/2013/02/13/revisiting-windows-azure-shared-access-signature/.
and here's the code from that post on uploading blob. It uses HttpWebRequest/HttpWebResponse instead of WebClient:
static void UploadBlobWithRestAPISasPermissionOnBlobContainer(string blobContainerSasUri)
{
string blobName = "sample.txt";
string sampleContent = "This is sample text.";
int contentLength = Encoding.UTF8.GetByteCount(sampleContent);
string queryString = (new Uri(blobContainerSasUri)).Query;
string blobContainerUri = blobContainerSasUri.Substring(0, blobContainerSasUri.Length - queryString.Length);
string requestUri = string.Format(CultureInfo.InvariantCulture, "{0}/{1}{2}", blobContainerUri, blobName, queryString);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestUri);
request.Method = "PUT";
request.Headers.Add("x-ms-blob-type", "BlockBlob");
request.ContentLength = contentLength;
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(Encoding.UTF8.GetBytes(sampleContent), 0, contentLength);
}
using (HttpWebResponse resp = (HttpWebResponse)request.GetResponse())
{
}
}
When testing against the blob emulator this is the code I need to get it working:
var connection = ConfigurationManager.AppSettings["AzureStorageConnectionString"];
var storageAccount = CloudStorageAccount.Parse(connection);
var client = new WebClient();
client.Headers.Add("x-ms-blob-type", "BlockBlob");
client.Headers.Add("x-ms-version", "2012-02-12");
client.UploadData(string.Format(#"{0}/$root/{1}{2}", storageAccount.BlobEndpoint, myFileName, sharedAccessSignature), "PUT", _content);

I want to recover the posts of my Facebook account to simple table, but I am facing some problems

I am using C# and ASP.NET to code this. I don't want the user to be forced to log in and authorize my facebook app, so I wrote this code to get my token that works fine:
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create("https://graph.facebook.com/oauth/access_token?client_id=MYID&client_secret=MYSECRET&user_id=MYUSERID&grant_type=client_credentials");
myRequest.Method = "GET";
WebResponse myResponse = myRequest.GetResponse();
StreamReader sr = new StreamReader(myResponse.GetResponseStream(), System.Text.Encoding.UTF8);
string result1 = sr.ReadToEnd();
sr.Close();
myResponse.Close();
string token = result1.Substring(13, result1.Length - 13);
Then I wrote this code to get my recent posts:
HttpWebRequest myRequest1 = (HttpWebRequest)WebRequest.Create(string.Format("{0}{1}","https://graph.facebook.com/app/posts?access_token=",token));
myRequest1.Method = "GET";
WebResponse myResponse1 = myRequest1.GetResponse();
//StreamReader sr1 = new StreamReader(myResponse1.GetResponseStream(), System.Text.Encoding.UTF8);
StreamReader sr1 = new StreamReader(myResponse1.GetResponseStream());
string result2 = sr1.ReadToEnd();
sr1.Close();
myResponse1.Close();
How can I quickly transform this JSON object into a table?