POST data using HttpClient - c#

I'm trying to POST a data to web using HttpClient but i can't succeed.
Here is my JSON web api
{
"Categories":[
{
"CategoryID":1,
"Category":"Category 1"
},
{
"CategoryID":2,
"Category":"Category 2"
}
]
}
i'am sending categories data to web my web developer send me above json to send a data from winform to web
Here is my code
IEnumerable<KeyValuePair<string, string>> paramt = new List<KeyValuePair<string, string>>()
{
new KeyValuePair<string,string>("CategoryID","1"),
new KeyValuePair<string,string>("Category","Pizza")
};
HttpContent q = new FormUrlEncodedContent(paramt);
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Clear();
client.BaseAddress = new Uri(url);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", api);
HttpResponseMessage response = client.PostAsync("api/categories", q).Result;
}
sorry for my english moderator please update my question

Thanks #John with the help of yours i did this
public class CategoryItem
{
public int CategoryID { get; set; }
public string Category { get; set; }
}
public class CategoriesRoot
{
public IList<CategoryItem> Categories { get; set; }
}
var tmp = new CategoriesRoot
{
Categories = new List<CategoryItem> {
new CategoryItem { CategoryID = 1, Category = "Pizza" }
}
};
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Clear();
client.BaseAddress = new Uri(url);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", api);
HttpResponseMessage response = client.PostAsJsonAsync("api/categories", tmp).Result;
}

Related

HTTP POST multipart form-data

I'm working on an App in Xamarin.Forms. I want to send the Post Request to an API with form-data. In the code below, it returns the success message, but the data isn't posted there.
public class Post {
public string ConnectionId { get; set; }
public string HolderFirstName { get; set; }
}
public async void SendProof(object sender, EventArgs e) {
try {
Uri URL = new Uri(string.Format("http://11.222.333.44:4000/api/v1/Proof/SendProofNameRequest"));
HttpClient _client = new HttpClient();
var post = new Post {ConnectionId = "9c12dba2-6cb9-4382-8c96-f1708a7e8816", HolderFirstName = "Carl Dreyer"};
var content = JsonConvert.SerializeObject(post);
var response = await _client.PostAsync(URL, new StringContent(content, Encoding.UTF8, "multipart/form-data"));
if (response.IsSuccessStatusCode) {
await DialogService.AlertAsync("Credential Proof Sent Successfully!");}
}
catch(Exception error) {
await DialogService.AlertAsync(error.Message); }
}
Binding for Button which triggers this Function.
public ICommand SendProofCommand => new Command(() => SendProof(default, default));
public async Task SendProof()
{
try {
HttpClient client = new HttpClient(new NativeMessageHandler());
client.BaseAddress = new Uri("http://11.222.333.44:4000/");
var postData = new List<KeyValuePair<string, string>>();
var nvc = new List<KeyValuePair<string, string>>();
nvc.Add(new KeyValuePair<string, string>("ConnectionId", "9c12dba2-6cb9-4382-8c96-f1708a7e8816"));
nvc.Add(new KeyValuePair<string, string>("HolderFirstName", "Bergman"));
var req = new HttpRequestMessage(HttpMethod.Post, "http://11.222.333.44:4000/" + "api/v1/Proof/SendProofNameRequest") { Content = new FormUrlEncodedContent(nvc) };
var res = await client.SendAsync(req);
if (res.IsSuccessStatusCode)
{
await DialogService.AlertAsync("Proof Sent Successfully!");
}
else
{
await DialogService.AlertAsync("Unsuccessfull!");
}
}
catch(Exception error) {
await DialogService.AlertAsync(error.Message);
}
}

.net HttpClient post api response not rendering properly

I am trying to get the html content from the news site https://nayapatrikadaily.com/news-article/2/News,
with the Http Post Request.
However in the response, page is returning the Unicode characters.
I am obstructed in converting the Unicode characters to html.
URL:
var nayapatrika = await ApiClient.PostAsync("https://nayapatrikadaily.com/ajax/pagination.php");
PostAsync:
public static async Task<HtmlDocument> PostAsync(string uri)
{
string responseJson = string.Empty;
var htmlDocument = new HtmlDocument();
var handler = new HttpClientHandler()
{
AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate
};
using (var client = new HttpClient(handler))
{
client.DefaultRequestHeaders.AcceptEncoding.Add(new StringWithQualityHeaderValue("gzip"));
client.DefaultRequestHeaders.AcceptEncoding.Add(new StringWithQualityHeaderValue("deflate"));
var content = new MultipartFormDataContent();
var values = new[]
{
new KeyValuePair<string, string>("perPage", "20"),
new KeyValuePair<string, string>("page", "2"),
new KeyValuePair<string, string>("cat", "1"),
};
foreach (var keyValuePair in values)
{
content.Add(new StringContent(keyValuePair.Value), keyValuePair.Key);
}
var response = await client.PostAsync(uri, content);
if (response.IsSuccessStatusCode)
{
responseJson = await response.Content.ReadAsStringAsync();
htmlDocument.LoadHtml(responseJson);
}
}
return htmlDocument;
}
On response the page is always returning with the below characters.
Deserializing the api response did the trick for me. As i noticed the responses it has two attributes: newsList and numPages.
I created the class: ResponseObj
public class ResponseObj
{
public string numPage { get; set; }
public string newsList { get; set; }
}
and deserliazed into ResponseObj
var obj = JsonConvert.DeserializeObject<ResponseObj>(responseJson);
var response = await client.PostAsync(uri, content);
if (response.IsSuccessStatusCode)
{
responseJson = await response.Content.ReadAsStringAsync();
var obj = JsonConvert.DeserializeObject<ResponseObj>(responseJson);
htmlDocument.LoadHtml(obj.newsList);
}

C# how to demonstrate api post from website

I'm trying to program automation QA test to register.
I need to demonstrate a register request to api from specific website
This is my code
public void TestApi()
{
string apiStatus = "";
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://my_base_api_address");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
//string fName = RegisterHandler.MakeNewUser();
var user = new RegisterModel()
{
public string UserEmail{ get; set; }
public int userId{ get; set; }
......
......
};
var response = client.PostAsJsonAsync("api/register/Register", user).Result;
if (response.IsSuccessStatusCode)
{
}
}
}
My code baseAddress is relevant to several websites but I need to test a specific one.
Where and how exactly should I put the testing website url?
Thanks in advance.

Calling WebApi with complex object parameter using WebClient

I need to call a WebApi using WebClient where have to pass an object as parameter. I have my WebApi method as similar to bellow code:
example URI: localhost:8080/Api/DocRepoApi/PostDoc
[HttpPost]
public string PostDoc (DocRepoViewModel docRepo)
{
return string.enpty;
}
and then DocRepoViewModel is:
public class DocRepoViewModel
{
public string Roles { get; set; }
public string CategoryName { get; set; }
public List<AttachmentViewModel> AttachmentInfo { get; set; }
}
AttachmentViewModel is:
public class AttachmentViewModel
{
public string AttachmentName { get; set; }
public byte[] AttachmentBytes { get; set; }
public string AttachmentType { get; set; }
}
New I need to call PostDoc method from my MVC controller (not javascript ajax). How can I pass this specific parameter that I can make the call and get all data in my WebApi method. Can we do it by WebClient? Or there are better way. Please help.
You could use the PostAsJsonAsync method as follows:
static async Task RunAsync()
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("localhost:8080/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// HTTP POST
var docViewModel = new DocRepoViewModel() { CategoryName = "Foo", Roles= "role1,role2" };
var attachmentInfo = new List<AttachmentViewModel>() { AttachmentName = "Bar", AttachmentType = "Baz", AttachmentBytes = File.ReadAllBytes("c:\test.txt" };
docViewModel.AttachmentInfo = attachmentInfo;
response = await client.PostAsJsonAsync("DocRepoApi/PostDoc", docViewModel);
if (response.IsSuccessStatusCode)
{
// do stuff
}
}
}
Asp .net reference
Check out following code.
string url = "Your Url";
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.KeepAlive = false;
request.ContentType = "application/json";
request.Method = "POST";
var entity = new Entity(); //your custom object.
byte[] bytes = System.Text.Encoding.ASCII.GetBytes(JsonConvert.SerializeObject(entity));
request.ContentLength = bytes.Length;
Stream data = request.GetRequestStream();
data.Write(bytes, 0, bytes.Length);
data.Close();
using (WebResponse response = request.GetResponse())
{
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
string message = reader.ReadToEnd();
var responseReuslt = JsonConvert.Deserialize<YourDataContract>(message);
}
}

HttpClient PutAsync doesn't send a parameter to api

On the controller Put is as following:
[HttpPut]
[ActionName("putname")]
public JsonResult putname(string name)
{
var response = ...
return Json(response);
}
The issue is on the when consuming this API via following
using (httpClient = new HttpClient())
{
string name = "abc";
string jsonString = JsonConvert.SerializeObject(name);
var requestUrl = new Uri("http:...../controller/putname/");
using (HttpContent httpContent = new StringContent(jsonString))
{
httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
HttpResponseMessage response = httpClient.PutAsync(requestUrl, httpContent).Result;
}
This code doesn't pass the parameter name to controller. I even tried changeing uri to /putname/" + name.
Here is what works for me:
var jsonString = "{\"appid\":1,\"platformid\":1,\"rating\":3}";
var httpContent = new StringContent(jsonString, Encoding.UTF8, "application/json");
var message = await _client.PutAsync(MakeUri("App/Rate"), httpContent);
Assert.AreEqual(HttpStatusCode.NoContent, message.StatusCode);
and my action method:
public void PutRate(AppRating model)
{
if (model == null)
throw new HttpResponseException(HttpStatusCode.BadRequest);
if (ModelState.IsValid)
{
// ..
}
}
and the model
public class AppRating
{
public int AppId { get; set; }
public int PlatformId { get; set; }
public decimal Rating { get; set; }
}
-Stan
For me it worked correctly:
string requestUrl = endpointUri + "/Files/";
var jsonString = JsonConvert.SerializeObject(new { name = "newFile.txt", type = "File" });
HttpContent httpContent = new StringContent(jsonString);
httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue ("application/json");
HttpClient hc = new HttpClient();
//add the header with the access token
hc.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", accessToken);
//make the put request
HttpResponseMessage hrm = (await hc.PostAsync(requestUrl, httpContent));
if (hrm.IsSuccessStatusCode)
{
//stuff
}

Categories

Resources