I want to send a Http request to some website(URL) and get a response(Basically I need to use GetAsync and PutAsync methods for this) and I need to do it with.NETCoreApp 1.1 in VS2017.
Do get and post
Setting headers
Ignore TLS cert errors
Does anyone have a simple example how to achieve this?
I found this example in the API documentation HttpClient Class, but it is not clear how to achieve the above points.
I spend a couple of hours looking at the source code corefx and came up with this simple example
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
namespace CoreFxHttpClientHandlerTest
{
public class Program
{
private static void Main(string[] args)
{
}
public static async Task<bool> Run()
{
var ignoreTls = true;
using (var httpClientHandler = new HttpClientHandler())
{
if (ignoreTls)
{
httpClientHandler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => { return true; };
}
using (var client = new HttpClient(httpClientHandler))
{
using (HttpResponseMessage response = await client.GetAsync("https://test.com/get"))
{
Console.WriteLine(response.StatusCode);
var responseContent = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseContent);
}
using (var httpContent = new StringContent("{ \"id\": \"4\" }", Encoding.UTF8, "application/json"))
{
var request = new HttpRequestMessage(HttpMethod.Post, "http://test.com/api/users")
{
Content = httpContent
};
httpContent.Headers.Add("Cookie", "a:e");
using (HttpResponseMessage response = await client.SendAsync(request))
{
Console.WriteLine(response.StatusCode);
var responseContent = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseContent);
}
}
}
}
return true;
}
}
}
See code in github.
Related
I am new to this and as my first, I'm trying to develop an Azure function to add a new item to column 'ID' to a Sharepoint online List via rest API in C#. I have written this code in the web portal of Azure and have adapted it into Visual Studio for the sake of troubleshooting. Please, anyone, provide some help as I cannot seem to get it working, Thanks.
using System;
using System.Configuration;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
using System.Net.Http.Headers;
using Newtonsoft.Json.Serialization;
using System.Security;
using System.Diagnostics;
using Microsoft.SharePoint.Client;
namespace ConsoleApp1
{
class Program
{
public static async Task<string> GetAuthTokenForSharePoint()
{
Console.WriteLine(" GetAuthTokenForSharePoint was executed!");
HttpClient client = new HttpClient();
string clientId = System.Configuration.ConfigurationManager.AppSettings["123aa123-1234-1234-b1c2-12ab0052c945"];
string clientSecret = System.Configuration.ConfigurationManager.AppSettings["HdvsavdshavshjdvHhhhsdgahsgjhwqj08="];
string tenantId = System.Configuration.ConfigurationManager.AppSettings["123a1a23-1ab4-4a44-b3c7-abc00d12345e"];
string spTenantUrl = System.Configuration.ConfigurationManager.AppSettings["https://mytenant.sharepoint.com"];
string spPrinciple = "00000003-0000-0ff1-ce00-000000000000";
string spAuthUrl = "https://accounts.accesscontrol.windows.net/" + tenantId + "/tokens/OAuth/2";
KeyValuePair<string, string>[] body = new KeyValuePair<string, string>[]
{
new KeyValuePair<string, string>("grant_type", "client_credentials"),
new KeyValuePair<string, string>("client_id", $"{clientId}#{tenantId}"),
new KeyValuePair<string, string>("resource", $"{spPrinciple}/{spTenantUrl}#{tenantId}".Replace("https://", "")),
new KeyValuePair<string, string>("client_secret", clientSecret)
};
var content = new FormUrlEncodedContent(body);
var contentLength = content.ToString().Length;
string token = "";
Console.WriteLine(content.ToString());
using (HttpResponseMessage response = await client.PostAsync(spAuthUrl, content))
{
if (response.Content != null)
{
Console.WriteLine("Something went wrong in getting token much earlier");
string responseString = await response.Content.ReadAsStringAsync();
JObject data = JObject.Parse(responseString);
token = data.Value<string>("access_token");
}
else
{
Console.WriteLine("Something went wrong in getting token");
}
}
return token;
}
public static async Task<string> GetDigestForSharePoint(string siteUrl, string token)
{
Console.WriteLine("GetDigestForSharePoint was executed!");
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);
client.DefaultRequestHeaders.Add("accept", "application/json;odata=verbose");
StringContent content = new StringContent("");
string spTenantUrl = System.Configuration.ConfigurationManager.AppSettings["https://mytenant.sharepoint.com"];
string digest = "";
// using (HttpResponseMessage response = await client.PostAsync())$"{spTenantUrl}{siteUrl}/_api/contextinfo"
using (HttpResponseMessage response = await client.PostAsync("https://mytenant.sharepoint.com/sites/mySite", content))
{
if (response.IsSuccessStatusCode)
{
string contentJson = response.Content.ReadAsStringAsync().Result;
JObject val = JObject.Parse(contentJson);
JToken d = val["d"];
JToken wi = d["GetContextWebInformation"];
digest = wi.Value<string>("FormDigestValue");
}
}
return digest;
}
public static async Task CreateSharePointListItem(string siteUrl, string listName, string itemTitle)
{
Console.WriteLine("CreateSharePointListItem was executed!");
try
{
var token = await GetAuthTokenForSharePoint();
Console.WriteLine(token);
var digest = await GetDigestForSharePoint(siteUrl, token);
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);
client.DefaultRequestHeaders.Add("accept", "application/json;odata=verbose");
client.DefaultRequestHeaders.Add("X-RequestDigest", digest);
client.DefaultRequestHeaders.Add("X-HTTP-Method", "POST");
HttpContent content = new StringContent($"{{ '__metadata': {{ 'type': 'SP.ListItem' }}, 'Title': '{itemTitle}'}}");
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
content.Headers.ContentType.Parameters.Add(new NameValueHeaderValue("odata", "verbose"));
string spTenantUrl = System.Configuration.ConfigurationManager.AppSettings["https://mytenant.sharepoint.com"];
using (HttpResponseMessage response = await client.PostAsync($"{spTenantUrl}{siteUrl}/_api/web/Lists/GetByTitle('{listName}')/items", content))
{
if (!response.IsSuccessStatusCode)
//log.Error($"The REST call to SharePoint failed: {response.StatusCode.ToString()}.");
Console.WriteLine(response.StatusCode.ToString());
}
}
catch (Exception ex)
{
//log.Error($"Could not write SharePoint list item: {ex}");
Console.WriteLine(ex);
}
}
public static async void Run()
{
Console.WriteLine("Run was executed!");
await CreateSharePointListItem("/sites/mySite", "myList", "ID");
}
static void Main(string[] args)
{
Program.Run();
}
}
}
I was following this example to use the VSTS REST API:
https://learn.microsoft.com/en-us/rest/api/vsts/search/code%20search%20results/fetch%20code%20search%20results?view=vsts-rest-4.1
The following url points directly to MyService.MyController in my org's VSTS:
https://my-corp.visualstudio.com/DefaultCollection/USOpsInfrastructure/USOpsInfrastructure%20Team/_git/MyService?path=%2FMyService.UI%2FControllers%2FMyController.cs&version=GBmaster
I tried to follow the example code with my implentation code below but a 404 response is returned without a detailed message. Any idea what the issue might be or how to debug?
private static async Task FindMyControllerRefs()
{
var baseUrl = "https://my-corp.almsearch.visualstudio.com";
using (var client = GetHttpClient(baseUrl))
{
var request = "{ \"searchText\": \"MyController\" }";
var projectUri = "/USOpsInfrastructure/USOpsInfrastructure%20Team/_git/MyService";
var searchUri = "/_apis/search/codesearchresults?api-version=4.1-preview.1";
var fullUri = projectUri + searchUri;
var response = await client.PostAsJsonAsync(fullUri, request);
//process the response
if (response.IsSuccessStatusCode)
{
var result = (await response.Content.ReadAsAsync<string>());
}
else //not 200
{
var message = await response.Content.ReadAsStringAsync();
}
}
}
private static HttpClient GetHttpClient(string baseUrl)
{
var client = new HttpClient(new HttpClientHandler() { UseDefaultCredentials = true });
client.BaseAddress = new Uri(baseUrl);
client.Timeout = Timeout.InfiniteTimeSpan;
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
return client;
}
The Code search REST API should be :
POST https://XXX.almsearch.visualstudio.com/{Project}/_apis/search/codesearchresults?api-version=4.1-preview.1
In you scenario please confirm what's the team project name: USOpsInfrastructure or MyService. If you are not sure about that, then you can have a try for each of them.
Besides, base on my test you need to add the "$top": 10 (you can change the number as needed) in the request body:
var request = "{ \"searchText\": \"MyController\",\"$top\": 10 }";
Below code works on my side: (Project name is "Git" in below sample)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
namespace CodeSearch
{
class Program
{
public static void Main()
{
Task t = CodeSearch();
Task.WaitAll(new Task[] { t });
}
private static async Task CodeSearch()
{
try
{
var username = "username";
var password = "Password/PAT";
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Add(
new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
Convert.ToBase64String(
System.Text.ASCIIEncoding.ASCII.GetBytes(
string.Format("{0}:{1}", username, password))));
string url = "https://{instance}.almsearch.visualstudio.com/Git/_apis/search/codesearchresults?api-version=4.1-preview.1";
var content = new StringContent("{\"searchText\": \"OwinStartupAttribute\", \"$top\": 10}", Encoding.UTF8, "application/json");
using (HttpResponseMessage response = client.PostAsync(url, content).Result)
{
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
Console.ReadLine();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
Console.ReadLine();
}
}
}
I am writing a code in C# to build the console to implement get request.
We were using POSTMAN to achieve the task but we decided to build our own.
I need to pass the user name and pw in headers of the request.
Since i am new to programming,can you guide me.
I have written below code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Http;
namespace ConsoleApp2
{
class Program
{
private static object response;
static void Main(string[] args)
{
GetRequest("https://www.google.com");
Console.ReadKey();
}
async static void GetRequest(string url)
{
using (HttpClient client = new HttpClient())
{
using (HttpResponseMessage response = await client.GetAsync(url))
{
using (HttpContent content = response.Content)
{
string mycontent = await content.ReadAsStringAsync();
Console.WriteLine(mycontent);
}
}
}
}
}
}
You can try following code snippet
HttpClient client = new HttpClient()
var byteArray = Encoding.ASCII.GetBytes("username:password1234");
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
DefaultRequestHeaders is not working, I have used below snippet for authentication
string _ContentType = "application/json";
httpWebRequest.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(_ContentType));
var _CredentialBase64 = "xxxxxxxxx=";
httpWebRequest.DefaultRequestHeaders.Add("Authorization", String.Format("Basic {0}", _CredentialBase64));
I need to send a GCM Notification On A button click in the android application made through xamarin.
I Have followed this tutorial https://developer.xamarin.com/guides/cross-platform/application_fundamentals/notifications/android/remote_notifications_in_android/
Button btnCLick = Findviewbyid<button>(resource.id.btnclikc);
btnCLick.Click += btnCLick_CLICK;
void btnCLick_Click (object sender, System.EventArgs e)
{
// Here i need to send my notification. I am not able to get it.
}
I Use a MessageSender.exe to send my notification but i cant make it into my application.
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
namespace MessageSender
{
class Program
{
public const string API_KEY = "API_KEY";
public const string MESSAGE = "MESSAGE";
static void Main(string[] args)
{
var jGcmData = new JObject();
var jData = new JObject();
jData.Add("message", MESSAGE);
jGcmData.Add("to", "/topics/global");
jGcmData.Add("data", jData);
var url = new Uri("https://gcm-http.googleapis.com/gcm/send");
try
{
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.TryAddWithoutValidation(
"Authorization", "key=" + API_KEY);
Task.WaitAll(client.PostAsync(url,
new StringContent(jGcmData.ToString(), Encoding.Default, "application/json"))
.ContinueWith(response =>
{
Console.WriteLine(response);
Console.WriteLine("Message sent: check the client device notification tray.");
}));
}
}
catch (Exception e)
{
Console.WriteLine("Unable to send GCM message:");
Console.Error.WriteLine(e.StackTrace);
}
}
}
}
I need to make this into my application button click in xamarin.Android
How Should i do that??
If I get your question right than your need a cross-platform HttpClient usage implementation for xamarin, right?
Try this: Consuming a RESTful Web Service. The topic might be a bit misleading but you should just get the HttpClient code you need.
async void MyNotificationPost(Uri uri, string json)
{
HttpClient client = new HttpClient();
var content = new StringContent (json, Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync(uri, content);
...
if (response.IsSuccessStatusCode)
{
...
}
}
In this example, the crossplatform Microsoft HTTP Client Libraries are used. If you do not like that you can use the conventional HttpWebRequest which is available in stock.
Task<WebResponse> HTTPRequestSend(
Uri uri,
byte[] bodyData,
CancellationToken cancellationToken)
{
HttpWebRequest request = WebRequest.CreateHttp(uri);
request.Method = "POST";
request.Headers["Accept"] = "application/json";
return Task.Factory.FromAsync<Stream>(
request.BeginGetRequestStream,
request.EndGetRequestStream,
null).ContinueWith(
reqStreamTask =>
{
using (reqStreamTask.Result)
{
reqStreamTask.Result.Write(bodyData, 0, bodyData.Length);
}
return Task.Factory.FromAsync<WebResponse>(
request.BeginGetResponse,
request.EndGetResponse,
null).ContinueWith(
resTask =>
{
return resTask.Result;
},
cancellationToken);
},
cancellationToken).Unwrap();
}
If you need that synchronous, be very careful not to get stuck in a deadlock. Do not forget to use ConfigureAwait(false) or the like.
P.S. I see you are using the ContinueWith and do not care for it's danger. Have a look here: ContinueWith is Dangerous, Too and do not miss the main article: StartNew is Dangerous
Actually I used the same as given in the question.
string API_KEY = "APIKEY";
var jGcmData = new JObject();
var jData = new JObject();
jData.Add("message", message);
jGcmData.Add("to", "/topics/global");
jGcmData.Add("data", jData);
var url = new Uri("https://gcm-http.googleapis.com/gcm/send");
try
{
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.TryAddWithoutValidation(
"Authorization", "key=" + API_KEY);
Task.WaitAll(client.PostAsync(url,
new StringContent(jGcmData.ToString(), Encoding.Default, "application/json"))
.ContinueWith(response =>
{
Console.WriteLine(response);
Console.WriteLine("Message sent: check the client device notification tray.");
}));
}
}
catch (Exception e)
{
Console.WriteLine("Unable to send GCM message:");
Console.Error.WriteLine(e.StackTrace);
}
It worked. Thanks for your Help. Brother #ZverevEugene
I have an incoming POST request from a program that consists of JSON data.
This is my server code:
static HttpListener _httpListener = new HttpListener();
static void ResponseThread()
{
while (true)
{
HttpListenerContext context = _httpListener.GetContext(); // get a context
// Now, you'll find the request URL in context.Request.Url
HttpListenerRequest request = context.Request;
string test = "";
using (http://System.IO (http://System.IO).Stream body = request.InputStream) // here we have data
{
using (http://System.IO (http://System.IO).StreamReader reader = new http://System.IO (http://System.IO).StreamReader(body, request.ContentEncoding))
{
test = reader.ReadToEnd();
}
}
Console.WriteLine(test);
byte[] _responseArray = Encoding.UTF8.GetBytes(test); // get the bytes to response
context.Response.OutputStream.Write(_responseArray, 0, _responseArray.Length); // write bytes to the output stream
context.Response.KeepAlive = false; // set the KeepAlive bool to false
context.Response.Close(); // close the connection
Console.WriteLine("Respone given to a request.");
}
}
static void Main(string[] args)
{
Console.WriteLine("Starting server...");
_httpListener.Prefixes.Add("http://localhost:5000/ (http://localhost:5000/)"); // add prefix "http://localhost:5000/ (http://localhost:5000/)"
_httpListener.Start(); // start server (Run application as Administrator!)
Console.WriteLine("Server started.");
Thread _responseThread = new Thread(ResponseThread);
_responseThread.Start(); // start the response thread
}
This is the posting code i'm using outside of the server code in a different project
static string httpPost(string json)
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://localhost:5000/");
httpWebRequest.ContentType = "text/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
return result;
}
}
and I want to display the "test" variable in my browser but for right now it isn't working at all. Nothing is displayed but if I just send some html it works. Is there anyway to get this working or parse it out so that it does work?
To augment my comment on your question, here's a "Hello World" of sorts using the Owin self hosted server. It mimics what your question was trying to do. First install NuGet package Microsoft.Owin.SelfHost. Then include the System.Net.Http and System.Net.Http.Formatting .Net framework references. Included also is a code example to call the self-hosted server.
using Microsoft.Owin;
using Microsoft.Owin.Hosting;
using Owin;
using System;
using System.IO;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
namespace StackOverflowAnswer
{
class Startup
{
public void Configuration(IAppBuilder app)
{
app.Use<RespondToRequestMiddleware>();
}
}
class RespondToRequestMiddleware : OwinMiddleware
{
public RespondToRequestMiddleware(OwinMiddleware next)
: base(next)
{
}
public async override Task Invoke(IOwinContext context)
{
// Perform request stuff...
// Could verify that the request Content-Type == application/json
// Could verify that the request method was POST.
bool isPost = context.Request.Method == "POST";
string test = null;
if (isPost)
{
using (StreamReader reader = new StreamReader(context.Request.Body))
{
test = await reader.ReadToEndAsync();
}
}
await Next.Invoke(context); // pass off request to the next middleware
if (isPost)
{
// Perform response stuff...
context.Response.ContentType = "application/json";
context.Response.StatusCode = 200;
await context.Response.WriteAsync(test);
Console.WriteLine("Response given to a request.");
}
}
}
class Program
{
static void Main(string[] args)
{
string url = "http://localhost:5000/";
using (WebApp.Start<Startup>(url))
{
Console.WriteLine($"Listening on {url}...");
using (HttpClient httpClient = new HttpClient())
{
string json = "{\"key\":\"value\", \"otherKey\":\"secondValue\"}";
// Typically use the extensions in System.Net.Http.Formatting in order to post a strongly typed object with HttpClient.PostAsJsonAsync<T>(url)
StringContent content = new StringContent(json, Encoding.UTF8, "application/json");
HttpResponseMessage response = httpClient.PostAsync(url, content).Result; // IMPORTANT: use await in an async method in the real world.
if (response.IsSuccessStatusCode)
{
string responseJson = response.Content.ReadAsStringAsync().Result; // Again: use await in an async method in the real world.
Console.WriteLine(responseJson); // In your method, return the string.
}
else
{
Console.WriteLine($"Unsuccessful {response.StatusCode} : {response.ReasonPhrase}");
}
}
Console.ReadLine(); // keep console from closing so server can keep listening.
}
}
}
}
In action:
Check out the Microsoft Owin/Katana site for more info.