I am using HttpClient to send the data to the server through C# console application using post .
The HttpClient PostAsync is unable to post the data I have tried to send in various format
i.e string content , binary content , stream content , http content through Dictionary object but the post is null and the server is returning the request invalid exception below is my code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Http;
using System.Windows;
using System.Windows.Input;
using System.IO;
using System.Web;
namespace ConsoleApplication1
{
class Program
{
string str = ""; int j = 0;
static void Main(string[] args)
{
Program df = new Program();
df.Started();
}
public async void Started()
{
string contentLength="0";
try
{
contentLength = await AccessTheWebAsync();
}
catch (Exception e)
{
}
Console.WriteLine(contentLength);
}
async Task<string> AccessTheWebAsync()
{
HttpClient client = new HttpClient();
string token = "qwerty1234";
string test = "1";
string postrequest = "<?xml version='1.0' encoding='UTF-8'?>" +
"<request> " +
"<rec>asdf1234</rec> " +
" <lid>9876</lid> " +
"</request> ";
Dictionary<string, string> dict = new Dictionary<string, string>();
dict.Add("token", token);
dict.Add("test", test);
dict.Add("request", postrequest);
HttpContent content = new FormUrlEncodedContent(dict);
Uri url = new Uri("http://example.com/");
Task<HttpResponseMessage> getStringTask = client.PostAsync(url, content);
HttpResponseMessage httpmesssage = await getStringTask;
Stream respons = await httpmesssage.Content.ReadAsStreamAsync();
StreamReader sr = new StreamReader(respons);
string response = sr.ReadToEnd();
return response;
}
}
}
thanks in advance
In a Console application, you need to wait for the operation to complete, either using Task.Wait, Console.ReadKey, or similar. Also, avoid async void:
static void Main(string[] args)
{
Program df = new Program();
df.StartedAsync().Wait();
}
public async Task StartedAsync()
Related
I'm trying to pass an URL to an API using a .net 2.0 webclient (unable to upgrade). The webclient call only works if there are no slashes in the encoded value. Any idea why it is failing and how to make it work?
using System.Net;
using System.Text;
using System.Web;
namespace ConsoleAppWebClient
{
class Program
{
static void Main(string[] args)
{
using (var client = new WebClient())
{
client.Encoding = Encoding.UTF8;
client.Headers[HttpRequestHeader.Accept] = "application/xml";
var requestUrl = HttpUtility.UrlEncode("https://www.somewebsite.com");
var stringResult = client.DownloadString("https://localhost:12345/api/getstuff/" + requestUrl);
}
}
}
}
The above doesnt work but the below works just fine
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System.Xml.Serialization;
using System.Web;
namespace ConsoleAppWebClient
{
class Program
{
static void Main(string[] args)
{
using (var client = new WebClient())
{
client.Encoding = Encoding.UTF8;
client.Headers[HttpRequestHeader.Accept] = "application/xml";
var requestUrl = HttpUtility.UrlEncode("https:www.somewebsite.com");
var stringResult = client.DownloadString("https://localhost:12345/api/getstuff/" + requestUrl);
}
}
}
}
It looks like requestUrl is meant to be a query parameter, but you're adding it to the URL's path.
The result is
https://localhost:12345/api/getstuff/https%3A%2F%2Fwww.somewebsite.com
"%" is an unsafe character which can lead to unpredictable results.
Instead, try making it a querystring parameter:
var requestUrl = HttpUtility.UrlEncode("https:www.somewebsite.com");
var stringResult = client.DownloadString(
"https://localhost:12345/api/getstuff/?requestUrl=" + requestUrl);
Now that the URL-encoded parameter is in the querystring instead of the path it should be okay.
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));
How can I make the following cURL call via C# console app.
curl -k https://serverName/clearprofile.ashx -H "Host: example.com"
I have tried CurlSharp. Unfortunately I could not build successfully this project because of missing libcurlshim64 assembly.
From here I understood that the best approach is by using HttpClient class, but I don`t know how exactly to make the above mentioned cURL call from my console application.
If you just want something simple I would use the HttpClient class built into the .Net Framework like this:
using System.Net.Http;
using System.Threading.Tasks;
namespace ScrapCSConsole
{
class Program
{
static void Main(string[] args)
{
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Host = "example.com";
Task<string> task = client.GetStringAsync("https://serverName/clearprofile.ashx");
task.Wait();
Console.WriteLine(task.Result);
}
}
}
For more complex stuff, you can also use the HttpWebRequest class like this:
using System;
using System.IO;
using System.Net;
namespace ScrapCSConsole
{
class Program
{
static void Main(string[] args)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://google.co.uk");
request.Host = "example.com";
HttpStatusCode code;
string responseBody = String.Empty;
try
{
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
code = response.StatusCode;
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
responseBody = reader.ReadToEnd();
}
}
}
catch (WebException webEx)
{
using (HttpWebResponse response = (HttpWebResponse)webEx.Response)
{
code = response.StatusCode;
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
responseBody = reader.ReadToEnd();
}
}
}
Console.WriteLine($"Status: {code}");
Console.WriteLine(responseBody);
}
}
}
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.
UPDATE TO POST ORIGIANAL POST AFTER THIS CODE --- this code is an update to what david has been helping me do its throwing one error need help
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.Specialized;
using System.Net;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string URL = "http://localhost/test2.php";
WebClient webClient = new WebClient();
NameValueCollection formData = new NameValueCollection();
formData["var1"] = formData["var1"] = string.Format("MachineName: {0}", System.Environment.MachineName);
formData["var2"] = ip();
byte[] responseBytes = webClient.UploadValues(URL, "POST", formData);
string responsefromserver = Encoding.UTF8.GetString(responseBytes);
Console.WriteLine(responsefromserver);
webClient.Dispose();
System.Threading.Thread.Sleep(5000);
}
public void ip()
{
String publicIP = "";
System.Net.WebRequest request = System.Net.WebRequest.Create("http://checkip.dyndns.org/");
using (System.Net.WebResponse response = request.GetResponse())
{
using (System.IO.StreamReader stream = new System.IO.StreamReader(response.GetResponseStream()))
{
publicIP = stream.ReadToEnd();
}
}
//Search for the ip in the html
int first = publicIP.IndexOf("Address: ") + 9;
int last = publicIP.LastIndexOf("</body>");
publicIP = publicIP.Substring(first, last - first);
Console.WriteLine(publicIP);
System.Threading.Thread.Sleep(5000);
}
}
}
this is the error I am getting
Error 2 - An object reference is required for the non-static field, method, or property 'ConsoleApplication1.Program.ip()'
I am trying to create a function that will send the out put as var2
I have this c# script
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication4
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("MachineName: {0}", System.Environment.MachineName);
System.Threading.Thread.Sleep(5000);
}
}
}
how can I change this so it outputs the string to a variable say "VAR2" and use it in this script
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.Specialized;
using System.Net;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string URL = "http://localhost/test2.php";
WebClient webClient = new WebClient();
NameValueCollection formData = new NameValueCollection();
formData["var1"] = "THIS IS WHERE VAR2 NEEDS TO BE ";
byte[] responseBytes = webClient.UploadValues(URL, "POST", formData);
string responsefromserver = Encoding.UTF8.GetString(responseBytes);
Console.WriteLine(responsefromserver);
webClient.Dispose();
System.Threading.Thread.Sleep(5000);
}
}
}
SO HOW CAN I ADD THE MACHINE NAME SCRIPT TO THIS FUNCTION AND THEN USE IT AS VAR2
any help would be brilliant
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication5
{
class Program
{
public static int Main(string[] args)
{
String publicIP = "";
System.Net.WebRequest request = System.Net.WebRequest.Create("http://checkip.dyndns.org/");
using (System.Net.WebResponse response = request.GetResponse())
{
using (System.IO.StreamReader stream = new System.IO.StreamReader(response.GetResponseStream()))
{
publicIP = stream.ReadToEnd();
}
}
//Search for the ip in the html
int first = publicIP.IndexOf("Address: ") + 9;
int last = publicIP.LastIndexOf("</body>");
publicIP = publicIP.Substring(first, last - first);
Console.WriteLine(publicIP);
System.Threading.Thread.Sleep(5000);
return 0;
}
}
}
her is the update david I would like to incude this script in my other script so it looks like this
formData["var1"] = formData["var1"] = string.Format("MachineName: {0}", System.Environment.MachineName);
formData["var2"] = "this is where this script needs to be ";
Why does it need to be in a separate application? If one application's output is going to be the command-line argument for another application's input, then they're both running on the same machine. Which means, in this case, they'd both get the same value from System.Environment.MachineName.
You can just get the value in the application where it's needed:
formData["var1"] = string.Format("MachineName: {0}", System.Environment.MachineName);