I am trying to make a PostAsync request with c#. The following is my code.
static void Main(string[] args)
{
CookieContainer cookies = new CookieContainer();
HttpClientHandler handler = new HttpClientHandler();
handler.CookieContainer = cookies;
using (var client = new HttpClient(handler))
{
using (HttpResponseMessage getResponse = client.GetAsync("http://google.com").Result)
{
CheckStatusCode(getResponse);
String header = getResponse.Headers.ToString();
var content = CreateCollection(getResponse.Content);
var _stringHeaderContent = header + "\r" + content;
HttpContent _content = new StringContent(_stringHeaderContent, Encoding.UTF8);
Console.WriteLine(_content);
using (HttpResponseMessage postResponse = client.PostAsync("http://google.com",_content).Result)
{
Console.WriteLine(postResponse.Headers);
CheckStatusCode(postResponse);
Console.WriteLine(postResponse.Headers);
}
}
}
}
methods:
public static void CheckStatusCode(HttpResponseMessage response)
{
if (response.StatusCode != HttpStatusCode.OK)
throw new Exception(String.Format(
"Server error (HTTP {0}: {1}).",
response.StatusCode,
response.ReasonPhrase));
else
Console.WriteLine("200");
}
public static String CreateCollection(HttpContent content)
{
var myContent = content.ReadAsStringAsync().Result;
HtmlNode.ElementsFlags.Remove("form");
string html = myContent;
var doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(html);
var input = doc.DocumentNode.SelectSingleNode("//*[#name='__Token']");
var token = input.Attributes["value"].Value;
//add all necessary component to collection
NameValueCollection collection = new NameValueCollection();
collection.Add("__Token", token);
collection.Add("returnURL", "");
collection.Add("Email", "11111111#hotmail.com");
collection.Add("Password", "1234");
String queryString = GenerateQueryString(collection);
return queryString;
}
public static string GenerateQueryString(NameValueCollection collection)
{
var array = (from key in collection.AllKeys
from value in collection.GetValues(key)
select string.Format("{0}={1}", WebUtility.UrlEncode(key), WebUtility.UrlEncode(value))).ToArray();
return string.Join("&", array);
}
The problem I am having with this code is nothing gets stored in _content. I am trying to make a postAsync request with the header and a part of the content joined. however when I make the postAsync request nothing is stored in _content. Therefore the request fails.
Can anyone explain to me how I can make a postAsync request with _stringHeaderContent?
Regards
This is the way how to use PostAsync:
...
var httpClient = new HttpClient();
var postData = new List<KeyValuePair<string, string>>();
postData.Add(new KeyValuePair<string, string>("a", "1"));
postData.Add(new KeyValuePair<string, string>("b", "2"));
var content = new FormUrlEncodedContent(postData);
var result = httpClient.PostAsync("http://127.0.0.1/a.php", content).Result;
...
Related
I used the following code to get a token value but error (The remote certificate is invalid according to the validation procedure.) returns Thanks for the guidance.
private static async Task<string> GetAccessToken()
{
using (var client = new HttpClient())
{
const string URL = "https://bime.net.iraneit.com:3023/BimeApiManager_Main/api/EITAuthentication/GetAppToken";
client.BaseAddress = new Uri(URL);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
ICollection<KeyValuePair<String, String>> postData = new Dictionary<String, String>();
postData.Add(new KeyValuePair<String, String>("appname", " "));
postData.Add(new KeyValuePair<String, String>("secret", " "));
FormUrlEncodedContent content = new FormUrlEncodedContent(postData);
var ttt = content;
var result = await client.PostAsync(URL, content);
var response = await client.PostAsync("appToken", content);
if (response.IsSuccessStatusCode)
{
string JString = await response.Content.ReadAsStringAsync();
object responseData = JsonConvert.DeserializeObject(JString);
return ((dynamic)responseData).access_token;
}
else
{
return null;
}
}
}
I'm working on Xamarin.Android App. I have to consume rest API of content type x-www-form-urlencoded. I'm unable to call the Rest API Successfully, before this, I consumed many web services but I'm working on this type of API first time. I'm stuck in this.
I tried two ways to consume it:
public static string makePostEncodedRequest(string url, string jsonparams)
{
string ret = "";
var httpwebrequest = (HttpWebRequest)WebRequest.Create(url);
httpwebrequest.ContentType = "application/x-www-form-urlencoded";
//httpwebrequest.Accept = Config.JsonHeaderAJ;
httpwebrequest.Method = Methods.Post.ToString();
byte[] bytearray = Encoding.UTF8.GetBytes(jsonparams);
using (var streamWriter = new StreamWriter(httpwebrequest.GetRequestStream(), Encoding.ASCII))
{
streamWriter.Write(bytearray);
streamWriter.Flush();
streamWriter.Close();
}
var httpResponse = (HttpWebResponse)httpwebrequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
ret = streamReader.ReadToEnd();
}
return ret;
}
the next one is:
Dictionary<string, string> requestParams = new Dictionary<string, string ();
requestParams.Add("value=", data1);
requestParams.Add("&value=", data2);
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));
HttpResponseMessage response = client.PostAsync(Config.DomainURl + Config.StudentLoginUrl, new FormUrlEncodedContent(requestParams)).Result;
var tokne = response.Content.ReadAsStringAsync().Result;
}
i have used the following code for authenticating user in my project might help you.
public static async Task<UserData> GetUserAuth(UserAuth userauth)
{
bool asd= CheckNetWorkStatus().Result;
if (asd)
{
var client = new HttpClient(new NativeMessageHandler());
client.BaseAddress = new Uri(UrlAdd);// ("http://192.168.101.119:8475/");
var postData = new List<KeyValuePair<string, string>>();
var dto = new UserAuth { grant_type = userauth.grant_type, password = userauth.password, username = userauth.username };
var nvc = new List<KeyValuePair<string, string>>();
nvc.Add(new KeyValuePair<string, string>("grant_type", userauth.grant_type));
nvc.Add(new KeyValuePair<string, string>("password", userauth.password));
nvc.Add(new KeyValuePair<string, string>("username", userauth.username));
var req = new HttpRequestMessage(HttpMethod.Post, UrlAdd + "token") { Content = new FormUrlEncodedContent(nvc) };
var res = await client.SendAsync(req);
if (res.IsSuccessStatusCode)
{
string result = await res.Content.ReadAsStringAsync();
var userData = JsonConvert.DeserializeObject<UserData>(result);
userData.ErrorMessage = "true";
return userData;
}
else
{
UserData ud = new UserData();
ud.ErrorMessage = "Incorrect Password";
return ud;
}
}
else
{
UserData ud = new UserData();
ud.ErrorMessage = "Check Ur Connectivity";
return ud;
}
}
Well... I read A LOT of questions here in StackOverflow, but still didn't get answer for it, I have this Web API controller:
public class ERSController : ApiController
{
[HttpGet]
public HttpResponseMessage Get()
{
var resposne = new HttpResponseMessage(HttpStatusCode.OK);
resposne.Content = new StringContent("test OK");
return resposne;
}
[HttpPost]
public HttpResponseMessage Post([FromUri]string ID,[FromBody] string Data)
{
var resposne = new HttpResponseMessage(HttpStatusCode.OK);
//Some actions with database
resposne.Content = new StringContent("Added");
return resposne;
}
}
and I wrote a small tester to it:
static void Main(string[] args)
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:54916/");
client.DefaultRequestHeaders.Accept.Clear();
var content = new StringContent("<data>Hello</data>", Encoding.UTF8, "application/json");
var response = client.PostAsync("api/ERS?ID=123", content);
response.ContinueWith(p =>
{
string result = p.Result.Content.ReadAsStringAsync().Result;
Console.WriteLine(result);
});
Console.ReadKey();
}
I always get NULL on the parameter Data in the API.
I tried adding those lines to the tester:
client.DefaultRequestHeaders
.Accept
.Add(new MediaTypeWithQualityHeaderValue("application/json"));
still NULL, I also replace the content with:
var values = new Dictionary<string, string>();
values.Add("Data", "Data");
var content = new FormUrlEncodedContent(values);
still NULL.
I tried switching the request to:
WebClient client = new WebClient();
client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
var values = new NameValueCollection();
values["Data"] = "hello";
var task = client.UploadValuesTaskAsync("http://localhost:54916/api/ERS?ID=123", values);
task.ContinueWith((p) =>
{
string response = Encoding.UTF8.GetString(p.Result);
Console.WriteLine(response);
});
but debugger still saying 'NO!' the Data is still NULL.
I do get the ID with no problem.
If you want to send it as a JSON string, you should do this (using Newtonsoft.Json):
var serialized = JsonConvert.SerializeObject("Hello");
var content = new StringContent(serialized, Encoding.UTF8, "application/json");
You almost got it right with FormUrlEncodedContent, what you had to do was send it with an empty name, like in this example:
var content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("", "Hello")
});
var response = client.PostAsync("api/ERS?ID=123", content);
public async Task NewMethodAsync()
{
try
{
HttpClient objClient = new HttpClient();
Uri requestUri = new Uri("https://approvalbotbeta.azurewebsites.net/api/token");
Dictionary<string, string> pairs = new Dictionary<string, string>();
var client_ID = "<CLIENT ID>";
var client_secret = "<SECRET KEY STRING>";
pairs.Add("grant_type", "client_credentials");
pairs.Add("reply_url", "http://localhost");
FormUrlEncodedContent httpContent = new FormUrlEncodedContent(pairs);
var encordedString = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(client_ID + ":" + client_secret));
objClient.DefaultRequestHeaders.Add("Authorization", "Basic " + encordedString);
HttpResponseMessage respon = await objClient.PostAsync("https://approvalbotbeta.azurewebsites.net/api/token", httpContent);
if (respon.IsSuccessStatusCode)
{
Console.WriteLine(respon.Content.ReadAsStringAsync().Result);
var ww = respon.Content.ReadAsStringAsync().Result;
var response = JsonConvert.DeserializeObject<Response>(ww);
Console.WriteLine(response.access_token);
var acc_tkn = response.access_token;
// Uri requesturi = new Uri("https://approvalbotbeta.azurewebsites.net/api/send");
// Dictionary<string, string> pairs2 = new Dictionary<string, string>();
// pairs2.Add("Content-Type", "application/json");
// FormUrlEncodedContent httpContent2 = new FormUrlEncodedContent(pairs2);
// objClient.DefaultRequestHeaders.Add("Authorization", "Bearer",+ acc_tkn);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
I coded this for getting access token, and got it. Now I want to get 200 status using this token and my URL. So what are the coding lines?
respon.StatusCode will get you 200.
If you mean that using this token you want to retrieve data from your API, use this:
using (var client = new HttpClient())
{
var url = "https://approvalbotbeta.azurewebsites.net/api/GetSomething";
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + acc_tkn);
var response = await client.GetStringAsync(url);
// Parse JSON/XML response.
}
GetSomething is the method you want to call.
acc_tkn you got in your posted code.
I need to make some api calls in C#. I'm using Web API Client from Microsoft to do that. I success to make some POST requests, but I don't know how to add the field "Body" into my requests. Any idea ?
Here's my code:
static HttpClient client = new HttpClient();
public override void AwakeFromNib()
{
base.AwakeFromNib();
notif_button.Activated += (sender, e) => {
};
tips_button.Activated += (sender, e) =>
{
Tip t1 = new Tip(title_tips.StringValue, pic_tips.StringValue, content_tips.StringValue, "TEST");
client.BaseAddress = new Uri("my_url");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
CreateProductAsync(t1).Wait();
};
}
static async Task<Uri> CreateProductAsync(Tip tips)
{
HttpResponseMessage response = await client.PostAsJsonAsync("api/add_tips", tips);
response.EnsureSuccessStatusCode();
return response.Headers.Location;
}
Step 1. Choose a type that derives from HttpContent. If you want to write a lot of content with runtime code, you could use a StreamContent and open some sort of StreamWriter on it. For something short, use StringContent. You can also derive your own class for custom content.
Step 2. Pass the content in a call to HttpClient.PostAsync.
Here's an example that uses StringContent to pass some JSON:
string json = JsonConvert.SerializeObject(someObject);
var httpContent = new StringContent(json, Encoding.UTF8, "application/json");
var httpResponse = await httpClient.PostAsync("http://www.foo.bar", httpContent);
See also How do I set up HttpContent?.
Thanks to this and this, I finally found the solution to send post requests with headers AND body content. Here's the code:
var cl = new HttpClient();
cl.BaseAddress = new Uri("< YOUR URL >");
int _TimeoutSec = 90;
cl.Timeout = new TimeSpan(0, 0, _TimeoutSec);
string _ContentType = "application/x-www-form-urlencoded";
cl.DefaultRequestHeaders.Add(key, value);
cl.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(_ContentType));
cl.DefaultRequestHeaders.Add("key", "value");
cl.DefaultRequestHeaders.Add("key", "value");
var _UserAgent = "d-fens HttpClient";
cl.DefaultRequestHeaders.Add("User-Agent", _UserAgent);
var nvc = new List<KeyValuePair<string, string>>();
nvc.Add(new KeyValuePair<string, string>("key of content", "value"));
var req = new HttpRequestMessage(HttpMethod.Post, "http://www.t-lab.fr:3000/add_tips") { Content = new FormUrlEncodedContent(nvc) };
var res = cl.SendAsync(req);
a little more understandable
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));
client.DefaultRequestHeaders.Add("Accept", "*/*");
var Parameters = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("Id", "1"),
};
var Request = new HttpRequestMessage(HttpMethod.Post, "Post_Url")
{
Content = new FormUrlEncodedContent(Parameters)
};
var Result = client.SendAsync(Request).Result.Content.ReadAsStringAsync();
}