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);
}
}
Related
Below is my JSON response from PHP Web API. I need this "tradeType" to be loaded in WPF ComboBox after checking "success"is true/false, If false display Error message shown in "message"
{
"success":"true",
"message":"Trade Type List",
"tradeType":[
{"id":1, "name":"Coaching Class"},
{"id":2,"name":"Food Supply"},
{"id":3,"name":"Marriage Bureau"}
]
}
I am new to WPF and Web API, what i have tried is
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://offline.localhost.in/");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.GetAsync("api/utilities/trade_types").Result;
if (response.IsSuccessStatusCode)
{
var jsonString = response.Content.ReadAsStringAsync();
Root myDeserializedClass = JsonConvert.DeserializeObject<List<TradeType>>(jsonString);
cmbTrade.ItemsSource = users;
}
else
{
MessageBox.Show("Error Code" + response.StatusCode + " : Message - " + response.ReasonPhrase);
}
var jsonString = response.Content.ReadAsStringAsync();
You are missing an await here so the call is fired but not awaited. Also have Task in var instead the string.
var jsonString = await response.Content.ReadAsStringAsync();
or use the non-async version.
public class TradeType
{
public int id { get; set; }
public string name { get; set; }
}
public class Root
{
public string success { get; set; }
public string message { get; set; }
public List<TradeType> tradeType { get; set; }
}
private void GetData()
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://offline.localhost.in/");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.GetAsync("api/utilities/trade_types").Result;
if (response.IsSuccessStatusCode)
{
var result = response.Content.ReadAsStringAsync().Result;
Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(result);
myDeserializedClass.tradeType.Insert(0, new TradeType { id = 0, name = "-Select-" });
cmbTrade.ItemsSource = myDeserializedClass.tradeType;
cmbTrade.DisplayMemberPath = "name";
cmbTrade.SelectedValuePath = "id";
cmbTrade.SelectedIndex = 0;
}
else
{
MessageBox.Show("Error Code" + response.StatusCode + " : Message - " + response.ReasonPhrase);
}
}
Hy Guys,
I'm trying to download data from a url by logging in with a php Web Service but I don't know how to do it.
If I make a POST request via postman inserting in BODY -> form-data the email and password, it gives me this:
{"Users": [{"email": "email#test.it", "nickname": "nickname", "image": "http: \ / \ / localhost \ / MyWebService \ / images \ /test_img.png "}]}
So I created a class in cs like this:
public class Users
{
[JsonProperty("users", NullValueHandling = NullValueHandling.Ignore)]
public User[] UsersUsers { get; set; }
}
public class User
{
[JsonProperty("email", NullValueHandling = NullValueHandling.Ignore)]
public string email { get; set; }
[JsonProperty("nickname", NullValueHandling = NullValueHandling.Ignore)]
public string nickname { get; set; }
[JsonProperty("password", NullValueHandling = NullValueHandling.Ignore)]
public string password { get; set; }
[JsonProperty("image", NullValueHandling = NullValueHandling.Ignore)]
public Uri image { get; set; }
}
Instead in the botton function I tried to write this code to contact the Service and make the call :
async private void login(Object sender, EventArgs e)
{
string email = lbl_email.Text;
string password = lbl_password.Text;
string url = "http://192.168.178.77/TestLoginURL/api/login.php";
var formContent = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("email", email),
new KeyValuePair<string, string>("password", password),
});
string contentType = "application/json";
JObject json = new JObject
{
{ "email", email},
{ "password", password }
};
HttpClient client = new HttpClient();
var response = await client.PostAsync(url, new StringContent(json.ToString(), Encoding.UTF8, contentType));
var data = await response.Content.ReadAsStringAsync();
var users = JsonConvert.DeserializeObject<Users>(data);
}
Obviously it is crushed and the error that gives me back is this:
Newtonsoft.Json.JsonReaderException
Unexpected character encountered while parsing value: <. Path '', line 0, position 0.
So, someone can help me?
Where am I wrong?
Thanks
Solved in this way :
async private void login(Object sender, EventArgs e)
{
string email = lbl_email.Text;
string password = lbl_password.Text;
string url = "http://192.168.178.77/TestLoginURL/api/login.php";
Users users = new Users();
FormUrlEncodedContent formContent = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("email", email),
new KeyValuePair<string, string>("password", password),
});
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Add("Accept", "application/json");
try
{
CancellationTokenSource cts = new CancellationTokenSource();
var responseMessage = client.PostAsync(url, formContent).Result;
var data = await responseMessage.Content.ReadAsStringAsync();
users = JsonConvert.DeserializeObject<Users>(data);
lbl_nickname.Text = users.UsersUsers[0].nickname;
}
catch (Exception ex)
{
ex.Message.ToString();
throw;
}
}
The way in which I passed the parameters to the url was practically wrong and consequently it gave me error by not recognizing the email and password I sent.
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);
}
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;
}
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
}