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);
}
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);
}
}
I'm doing a POST method to an end point with a PDF that is converted to base64 but I'm receiving a HTTP 406 CODE. I included in the body the application/pdf for mime type and I included the necessary header to accept my POST request but still I'm receiving the 406 code. Does the json body has any connection on receiving the 406 code or am I having a problems on my header? Please see attached image for the details of the end point and json body.
public class MyFile
{
[JsonProperty("mime")]
public string MimeType { get; set; }
[JsonProperty("data")]
public string Base64Data { get; set; }
}
public class PdfFile
{
[JsonProperty("file")]
public MyFile myFile { get; set; }
}
string pdfBase64;
const string pdfFileName = "file.pdf";
using (var pdfStream = await FileSystem.OpenAppPackageFileAsync(pdfFileName))
{
using (var pdfReader = new StreamReader(pdfStream))
{
var fileContents = await pdfReader.ReadToEndAsync();
pdfBase64 = Convert.ToBase64String(Encoding.UTF8.GetBytes(fileContents));
}
}
var file = new MyFile();
var pdf = new PdfFile();
file.MimeType = "application/pdf";
file.Base64Data = "base64-data=" + pdfBase64;
pdf.myFile = file;
var jsonContent = JsonConvert.SerializeObject(pdf.myFile);
string baseUrl = "https://goodmorning-axa-dev.azure-api.net/upload";
HttpClient httpClient = new HttpClient();
httpClient.DefaultRequestHeaders
.Accept
.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Post, baseUrl);
requestMessage.Content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
requestMessage.Headers.Add("x-axa-api-key", apiKey);
HttpResponseMessage responseMessage = await httpClient.SendAsync(requestMessage);
string responseAsString = await responseMessage.Content.ReadAsStringAsync();
if (responseAsString != null)
{
Console.WriteLine(responseAsString);
}
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);
}
}
First , a function that creates the token.
Then, calls GetClient(real token)
public static HttpClient GetClient(string token)
{
HttpClient client = new HttpClient();
HttpContent content = new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>("ContentType", "application/json"), new KeyValuePair<string, string>("Authorization", "Bearer '" + token + "'") });
var response = client.PostAsync(new Uri("https://api.sandbox.paypal.com/v2/checkout/orders"), content).Result;
if (response.IsSuccessStatusCode)
{
var responseContent = response.Content;
string responseString = responseContent.ReadAsStringAsync().Result;
}
return client;
}
The error is:
{StatusCode: 401, ReasonPhrase: 'Unauthorized', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{Paypal-Debug-Id: 5341e7ff8a884
Cache-Control: no-store, must-revalidate, no-cache, max-age=0
Date: Mon, 10 Feb 2020 05:36:37 GMT
Content-Length: 244
Content-Type: application/json
}}
What is the fix for such a thing??
There are two main parts of HTTP request that you have to understand to make this work:
Headers
Content
Headers is the first part of HTTP request which contains information about request like authorization, content length, content format, etc.
Second part is content. This is your actual data that you want to pass to the server. Content can be formatted in many different ways and your headers are supposed to inform server which type of formatting is used. Two of those formats that are referenced in your snippet are:
Form Url/Encoded - this data type is typicaly used with HTML forms. When you have something like
<form>
<input name="key1" value="value1"/>
<input name="key2" value="value2"/>
</form>
this form data is encoded as key1=value1&key2=value2.
Json - this is what you want to use for calling PayPal API, it's basically just Json structure appended as content with appropiate headers informing server that it should parse content as Json.
You are having problems because you are conflating headers with content and Form/UrlEncoded and Json content types. FormUrlEncodedContent constructor expects list of form key/value pairs, not headers and when you pass content-type and authorization to it, those key/value pairs are treated as data, not headers. This is where 401 error comes from as server is looking for authorization header not key/value pair in content. Try something like this:
public static HttpClient GetClient(string token)
{
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
var yourContent = new
{
key1 = "value1",
key2 = "value2"
};
var jsonContent = JsonConvert.SerializeObject(yourContent);
var content = new StringContent(jsonContent, Encoding.ASCII, "application/json");
var response = client.PostAsync(new Uri("https://api.sandbox.paypal.com/v2/checkout/orders"), content).Result;
if (response.IsSuccessStatusCode)
{
var responseContent = response.Content;
string responseString = responseContent.ReadAsStringAsync().Result;
}
return client;
}
First of all, I moved authentication from content to headers. You just need to create a new AuthenticationHeaderValue and pass "Bearer" as scheme (I haven't looked it up, but from your code I assume that API used Bearer authentication scheme).
Next, it seems that you want to use Json content-type. So you have to genereate Json as content. I perform that using anonymous data type and passing it to JsonConvert (you'll need Newtonsoft.Json package, if you copy this code Visual Studio should automaticaly suggest installing that package for you).
Finally, to add Json content to request you should use StringContent and pass both your generated Json string and content-type "application/json".
EDIT:
Tested your code, I assume your latest error was no longer 401, but rather 400 - Bad Request, caused by invalid content structure. Or it might have been 401 caused by invalid token parsing (maybe response length differs a bit?). Either way, updated code to correctly convert objects back and forth to JSON.
public class TokenResponse
{
[JsonProperty(PropertyName = "scope")]
public string Scope { get; set; }
[JsonProperty(PropertyName = "access_token")]
public string AccessToken { get; set; }
[JsonProperty(PropertyName = "token_type")]
public string TokenType { get; set; }
[JsonProperty(PropertyName = "app_id")]
public string AppId { get; set; }
[JsonProperty(PropertyName = "expires_in")]
public int ExpiresIn { get; set; }
[JsonProperty(PropertyName = "nonce")]
public string Nonce { get; set; }
}
public class Amount
{
[JsonProperty(PropertyName = "currency_code")]
public string CurrencyCode { get; set; }
[JsonProperty(PropertyName = "value")]
public string Value { get; set; }
}
public class PurchaseUnit
{
[JsonProperty(PropertyName = "amount")]
public Amount Amount { get; set; }
}
public class OrdersRequest
{
[JsonProperty(PropertyName = "intent")]
public string Intent { get; set; }
[JsonProperty(PropertyName = "purchase_units")]
public PurchaseUnit[] PurchaseUnits { get; set; }
}
public static void CreateToken()
{
var client = new HttpClient();
byte[] authBytes = Encoding.ASCII.GetBytes("user:pass");
string base64Auth = Convert.ToBase64String(authBytes);
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", base64Auth);
var content = new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>("grant_type", "client_credentials") });
var response = client.PostAsync(new Uri("https://api.sandbox.paypal.com/v1/oauth2/token"), content).Result;
if (response.IsSuccessStatusCode)
{
var tokenResponse = JsonConvert.DeserializeObject<TokenResponse>(response.Content.ReadAsStringAsync().Result);
GetClient(tokenResponse.AccessToken);
}
}
public static HttpClient GetClient(string token)
{
var client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
var request = new OrdersRequest
{
Intent = "CAPTURE",
PurchaseUnits = new PurchaseUnit[] { new PurchaseUnit
{
Amount = new Amount
{
CurrencyCode = "USD",
Value = "100.0"
}
}
}
};
var jsonContent = JsonConvert.SerializeObject(request);
var content = new StringContent(jsonContent, Encoding.ASCII, "application/json");
var response = client.PostAsync(new Uri("https://api.sandbox.paypal.com/v2/checkout/orders"), content).Result;
if (response.IsSuccessStatusCode)
{
var responseString = response.Content.ReadAsStringAsync().Result;
}
return client;
}
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
}