I want to send a http post request and capture the response. I have written following code.
System.Net.WebRequest req = System.Net.WebRequest.Create(URI);
req.Proxy = new System.Net.WebProxy(ProxyString, true);
//Add these, as we're doing a POST
req.ContentType = "application/x-www-form-urlencoded";
req.Method = "POST";
//We need to count how many bytes we're sending.
//Post'ed Faked Forms should be name=value&
byte [] bytes = System.Text.Encoding.ASCII.GetBytes(Parameters);
req.ContentLength = bytes.Length;
System.IO.Stream os = req.GetRequestStream ();
os.Write (bytes, 0, bytes.Length); //Push it out there
os.Close ();
System.Net.WebResponse resp = req.GetResponse();
if (resp== null) return null;
System.IO.StreamReader sr =
new System.IO.StreamReader(resp.GetResponseStream());
return sr.ReadToEnd().Trim();
Update 1:
I tried making use of PostAsync method. Still the same result.
public static async void Req()
{
using (var client = new HttpClient())
{
var values = new Dictionary<string, string>
{
{ "type1", "val1" },
{ "type2", "val2" },
{ "type3", "val3"}
};
var content = new FormUrlEncodedContent(values);
var r1 = await client.PostAsync(URL, content);
var responseString = await r1.Content.ReadAsStringAsync();
Console.WriteLine(responseString);
Console.ReadLine();
}
}
But its capturing only partial response. My Page takes 10-12 seconds to load. How do I make my script wait and capture complete response?
This could be due to that the response is encoded in som other encoding then UTF8 that StreamReader defaults to. Please check the encoding of the response and alter the call to streamreader from
new System.IO.StreamReader(resp.GetResponseStream());
to
new System.IO.StreamReader(resp.GetResponseStream(), Encoding.ASCII);
for ASCII encoding
working code. Just pass the correct parameters to the method.
public static async void Req()
{
using (var client = new HttpClient())
{
var values = new Dictionary<string, string>
{
{ "type1", "val1" },
{ "type2", "val2" },
{ "type3", "val3"}
};
var content = new FormUrlEncodedContent(values);
var r1 = await client.PostAsync(URL, content);
var responseString = await r1.Content.ReadAsStringAsync();
Console.WriteLine(responseString);
Console.ReadLine();
}
}
}
Related
Because of Net 6.0 usage I'm frustrated how to convert old HttpWebResponse to httpClient
Could someone help me to handle it right?
I have httpClient request
var handler = new HttpClientHandler();
if (handler.SupportsAutomaticDecompression)
{
handler.AutomaticDecompression = DecompressionMethods.GZip |
DecompressionMethods.Deflate;
}
var httpClient = new HttpClient(handler);
httpClient.SendAsync(new HttpRequestMessage(new HttpMethod.Post, url));
And I have old HttpWebResponse
using (var dataStream = httpWebRequest.GetRequestStream())
{
var reqDataByte = Encoding.GetEncoding(encoding).GetBytes(reqData);
dataStream.Write(reqDataByte, 0, reqDataByte.Length);
}
using (var httpWebResponse = (HttpWebResponse) httpWebRequest.GetResponse())
{
var responseStream = httpWebResponse.GetResponseStream();
if (responseStream != null)
using (var streamReader =
new StreamReader(responseStream, Encoding.GetEncoding(encoding)))
{
getString = streamReader.ReadToEnd();
}
}
Couldn't understand how to handle respond with httpClient right
using var dataStream = httpClient.GetAsync(url, HttpCompletionOption.ResponseHeadersRead);
var reqDataByte = Encoding.GetEncoding(encoding).GetBytes(reqData);
dataStream.CopyToAsync(reqDataByte, 0, reqDataByte.Length);
using var response = (HttpWebResponse) httpClient.GetResponse();
var responseStream = response.GetResponseStream();
using var streamReader =
new StreamReader(responseStream, Encoding.GetEncoding(encoding));
getString = streamReader.ReadToEnd();
If you are trying to simply post raw bytes and get a string response back it is quite simple. You will need this to be an async method and await the async calls.
var reqDataByte = Encoding.GetEncoding(encoding).GetBytes(reqData);
var response = await httpClient.PostAsync(url, new ByteArrayContent(reqDataByte));
if (response.IsSuccessStatusCode)
{
getString = await response.Content.ReadAsStringAsync();
}
else
{
//Handle any unsuccessful post
}
please, help me with POST api request in C#.I dont know how to correctly send parameters „key“, „signature“ and „nonce“ in POST request. It constantly tells me "Missing key, signature and nonce parameters“.
HttpWebRequest webRequest =(HttpWebRequest)System.Net.WebRequest.Create("https://www.bitstamp.net/api/balance/");
if (webRequest != null)
{
webRequest.Method = HttpMethod.Post;
webRequest.ContentType = "application/json";
webRequest.UserAgent = "BitstampBot";
byte[] data = Convert.FromBase64String(apisecret);
string nonce = GetNonce().ToString();
var prehash = nonce + custID + apikey;
string signature = HashString(prehash, data);
body = Serialize(new
{
key=apikey,
signature=signature,
nonce=nonce
});
if (!string.IsNullOrEmpty(body))
{
var data1 = Encoding.UTF8.GetBytes(body);
webRequest.ContentLength = data1.Length;
using (var stream = webRequest.GetRequestStream()) stream.Write(data1, 0, data1.Length);
}
using (Stream s = webRequest.GetResponse().GetResponseStream())
{
using (StreamReader sr = new System.IO.StreamReader(s))
{
contentBody = await sr.ReadToEndAsync();
return contentBody;
}
}
}
The "Request parameters" as Bitstamp specifies in the docs is actually supposed to be sent with content type "application/x-www-form-urlencoded" instead of "application/json".
I would also use HttpClient to perform the post as that has a much more simple setup to perform Http requests
using (var client = new HttpClient())
{
var content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("key", apikey),
new KeyValuePair<string, string>("signature", signature),
new KeyValuePair<string, string>("nonce", nonce)
});
var result = await client.PostAsync("https://www.bitstamp.net/api/balance/", content);
string resultContent = await result.Content.ReadAsStringAsync();
}
I want to consume rest api having post method in my project (web)/Windows service(C#).
Url : https://sampleurl.com/api1/token
I need to pass username and password for generating token.
I have written code like this.
string sURL = "https://sampleurl.com/api1/token/Actualusername/Actualpassword";
WebRequest wrGETURL;
wrGETURL = WebRequest.Create(sURL);
wrGETURL.Method = "POST";
wrGETURL.ContentType = #"application/json; charset=utf-8";
wrGETURL.ContentLength = 0;
HttpWebResponse webresponse = wrGETURL.GetResponse() as HttpWebResponse;
Encoding enc = System.Text.Encoding.GetEncoding("utf-8");
// read response stream from response object
StreamReader loResponseStream = new StreamReader(webresponse.GetResponseStream(), enc);
// read string from stream data
string strResult = loResponseStream.ReadToEnd();
// close the stream object
loResponseStream.Close();
// close the response object
webresponse.Close();
Response.Write(strResult);
I am getting error: No connection could be made because the target machine actively refused it
Is it right way to consume rest api in C#?
This all very much depend on the API's documentation, but to write data to the request body, get the request stream and then write the string to the stream.
again, this depends on what the API you are authenticating with and without knowing which one is guesswork on my part.
string sURL = "https://sampleurl.com/api1/token";
WebRequest wrGETURL;
wrGETURL = WebRequest.Create(sURL);
wrGETURL.Method = "POST";
wrGETURL.ContentType = #"application/json; charset=utf-8";
using (var stream = new StreamWriter(wrGETURL.GetRequestStream()))
{
var bodyContent = new
{
username = "Actualusername",
password = "Actualpassword"
}; // This will need to be changed to an actual class after finding what the specification sheet requires.
var json = JsonConvert.SerializeObject(bodyContent);
stream.Write(json);
}
HttpWebResponse webresponse = wrGETURL.GetResponse() as HttpWebResponse;
Encoding enc = System.Text.Encoding.GetEncoding("utf-8");
// read response stream from response object
StreamReader loResponseStream = new StreamReader(webresponse.GetResponseStream(), enc);
// read string from stream data
string strResult = loResponseStream.ReadToEnd();
// close the stream object
loResponseStream.Close();
// close the response object
webresponse.Close();
Response.Write(strResult);
Consume API with Basic Authentication in C#
class Program
{
static void Main(string[] args)
{
BaseClient clientbase = new BaseClient("https://website.com/api/v2/", "username", "password");
BaseResponse response = new BaseResponse();
BaseResponse response = clientbase.GetCallV2Async("Candidate").Result;
}
public async Task<BaseResponse> GetCallAsync(string endpoint)
{
try
{
HttpResponseMessage response = await client.GetAsync(endpoint + "/").ConfigureAwait(false);
if (response.IsSuccessStatusCode)
{
baseresponse.ResponseMessage = await response.Content.ReadAsStringAsync();
baseresponse.StatusCode = (int)response.StatusCode;
}
else
{
baseresponse.ResponseMessage = await response.Content.ReadAsStringAsync();
baseresponse.StatusCode = (int)response.StatusCode;
}
return baseresponse;
}
catch (Exception ex)
{
baseresponse.StatusCode = 0;
baseresponse.ResponseMessage = (ex.Message ?? ex.InnerException.ToString());
}
return baseresponse;
}
}
public class BaseResponse
{
public int StatusCode { get; set; }
public string ResponseMessage { get; set; }
}
public class BaseClient
{
readonly HttpClient client;
readonly BaseResponse baseresponse;
public BaseClient(string baseAddress, string username, string password)
{
HttpClientHandler handler = new HttpClientHandler()
{
Proxy = new WebProxy("http://127.0.0.1:8888"),
UseProxy = false,
};
client = new HttpClient(handler);
client.BaseAddress = new Uri(baseAddress);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var byteArray = Encoding.ASCII.GetBytes(username + ":" + password);
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
baseresponse = new BaseResponse();
}
}
I am new to MVC and C#, so sorry if this question seems too basic.
For a HttpPost Controller like below, how do to call this method directly from a client-side program written in C#, without a browser (NOT from a UI form in a browser with a submit button)? I am using .NET 4 and MVC 4.
I am sure the answer is somehwere on the web, but haven't found one so far. Any help is appreciated!
[HttpPost]
public Boolean PostDataToDB(int n, string s)
{
//validate and write to database
return false;
}
For example with this code in the server side:
[HttpPost]
public Boolean PostDataToDB(int n, string s)
{
//validate and write to database
return false;
}
You can use different approches:
With WebClient:
using (var wb = new WebClient())
{
var data = new NameValueCollection();
data["n"] = "42";
data["s"] = "string value";
var response = wb.UploadValues("http://www.example.org/receiver.aspx", "POST", data);
}
With HttpRequest:
var request = (HttpWebRequest)WebRequest.Create("http://www.example.org/receiver.aspx");
var postData = "n=42&s=string value";
var data = Encoding.ASCII.GetBytes(postData);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
var response = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
With HttpClient:
using (var client = new HttpClient())
{
var values = new List<KeyValuePair<string, string>>();
values.Add(new KeyValuePair<string, string>("n", "42"));
values.Add(new KeyValuePair<string, string>("s", "string value"));
var content = new FormUrlEncodedContent(values);
var response = await client.PostAsync("http://www.example.org/receiver.aspx", content);
var responseString = await response.Content.ReadAsStringAsync();
}
With WebRequest
WebRequest request = WebRequest.Create ("http://www.example.org/receiver.aspx");
request.Method = "POST";
string postData = "n=42&s=string value";
byte[] byteArray = Encoding.UTF8.GetBytes (postData);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteArray.Length;
Stream dataStream = request.GetRequestStream ();
dataStream.Write (byteArray, 0, byteArray.Length);
dataStream.Close ();
//Response
WebResponse response = request.GetResponse ();
Console.WriteLine (((HttpWebResponse)response).StatusDescription);
dataStream = response.GetResponseStream ();
StreamReader reader = new StreamReader (dataStream);
string responseFromServer = reader.ReadToEnd ();
Console.WriteLine (responseFromServer);
reader.Close ();
dataStream.Close ();
response.Close ();
see msdn
You can use
First of all you should return valid resutl:
[HttpPost]
public ActionResult PostDataToDB(int n, string s)
{
//validate and write to database
return Json(false);
}
After it you can use HttpClient class from Web Api client libraries NuGet package:
public async bool CallMethod()
{
var rootUrl = "http:...";
bool result;
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(_rootUrl);
var response= await client.PostAsJsonAsync(methodUrl, new {n = 10, s = "some string"});
result = await response.Content.ReadAsAsync<bool>();
}
return result;
}
You can also use WebClient class:
[HttpPost]
public Boolean PostDataToDB(int n, string s)
{
//validate and write to database
return false;
}
public async bool CallMethod()
{
var rootUrl = "http:...";
bool result;
using (var client = new WebClient())
{
var col = new NameValueCollection();
col.Add("n", "1");
col.Add("s", "2");
var res = await client.UploadValuesAsync(address, col);
string res = Encoding.UTF8.GetString(res);
result = bool.Parse(res);
}
return result;
}
If you decide to use HttpClient implementation. Do not create and dispose of HttpClient for each call to the API. Instead, re-use a single instance of HttpClient. You can achieve that declaring the instance static or implementing a singleton pattern.
Reference: https://aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong/
How to implement singleton (good starting point, read the comments on that post): https://codereview.stackexchange.com/questions/149805/implementation-of-a-singleton-httpclient-with-generic-methods
Hopefully below code will help you
[ActionName("Check")]
public async System.Threading.Tasks.Task<bool> CheckPost(HttpRequestMessage request)
{
string body = await request.Content.ReadAsStringAsync();
return true;
}
what I want is simple, I want to read a text file from my website via my application, I managed to do this in C# but not in metro apps, here my code in C#
WebClient client = new WebClient();
Stream stream = client.OpenRead(strURL);
StreamReader reader = new StreamReader(stream);
String content = reader.ReadToEnd();
return content;
besides the above code I also tried the code below, but still failed
HttpWebRequest request = (HttpWebRequest)
WebRequest.Create(strURL);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream resStream = response.GetResponseStream();
string tempString = null;
int count = 0;
byte[] buf = new byte[1000];
StringBuilder sb = new StringBuilder();
do
{
count = resStream.Read(buf, 0, buf.Length);
if (count != 0)
{
tempString = Encoding.Unicode.GetString(buf, 0, count);
sb.Append(tempString);
}
}
return sb.ToString();
I think the problem is in the WebClient and GetResponse () which is not known in metro apps
You should be able to use System.Net.Http.HttpClient and HttpResponseMessage, as they are included on http://msdn.microsoft.com/en-us/library/windows/apps/hh454046.aspx.
There is an example on http://msdn.microsoft.com/en-us/library/system.net.http.httpclient.aspx:
static async void Main()
{
try
{
// Create a New HttpClient object.
HttpClient client = new HttpClient();
HttpResponseMessage response = await client.GetAsync("http://www.contoso.com/");
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
// Above three lines can be replaced with new helper method in following line
// string body = await client.GetStringAsync(uri);
Console.WriteLine(responseBody);
}
catch(HttpRequestException e)
{
Console.WriteLine("\nException Caught!");
Console.WriteLine("Message :{0} ",e.Message);
}
}
var httpClient = new HttpClient();
var text = await httpClient.GetStringAsync(uri);
Wrapped up in an async method of course