My CurrentCode:
using (var client = new HttpClient
{
Timeout = TimeSpan.FromMilliseconds(2000)
})
{
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = await client.GetAsync(new Uri(Constants.mUrl));
// convert stream to string
StreamReader reader = new StreamReader(respons);
var myItems = Newtonsoft.Json.JsonConvert.DeserializeObject<ModelClassObject>(response);
return myItems;
}
Use ReadAsStreamAsync on the content of the response
using(var response = await client.GetAsync(new Uri(Constants.mUrl))) {
var stream = await response.Content.ReadAsStreamAsync();
//...
}
If you want to parse JOSN directly from the response, then
using(var response = await client.GetAsync(new Uri(Constants.mUrl))) {
var myItems = await response.Content.ReadAsAsync<ModelClassObject>();
return myItems;
}
Related
I am trying to call an api(POST method) with HttpClient.PostAsJsonAsync. However, it stopped at httpClient.PostAsJsonAsync without any exception.
The source code as below:
public static async Task<oResult> PostApi(string JSON_sObject, string sEnd_Url) {
oResult oResult = new oResult();
var Data = JsonConvert.DeserializeObject(JSON_sObject);
var Url = "http://localhost:44340/" + sEnd_Url;
HttpClient httpClient = new HttpClient();
try {
httpClient.DefaultRequestHeaders.Accept.Clear();
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await httpClient.PostAsJsonAsync(new Uri(Url), Data); // it stopped here
if (response.IsSuccessStatusCode)
{
var sResponse_content = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<oResult>(sResponse_content);
}
else
{
return oResult;
}
}
catch (Exception ex)
{
LogFile(ex);
return oResult;
}
}
Please advice me if any issue from the source code.
Thank you
you should not trying serialize deserialize twice
remove from your code
var Data = JsonConvert.DeserializeObject(JSON_sObject);
and replace
HttpResponseMessage response = await httpClient.PostAsJsonAsync(new Uri(Url), Data);
with this
var content = new StringContent(JSON_sObject, Encoding.UTF8, "application/json");
var response = await client.PostAsync(sEnd_Url, content);
also fix base httpclient address
var baseUri= #"http://localhost:44340";
using HttpClient client = new HttpClient { BaseAddress = new Uri(baseUri) };
try {
I writing UWP app.
I need to send POST request with json to server
Here is my code for downloading JSON and writing to value:
public async void AllOrders_down()
{
string url = "http://api.simplegames.com.ua/index.php/?wc_orders=all_orders";
var json = await FetchAsync(url);
List<RootObject> rootObjectData = JsonConvert.DeserializeObject<List<RootObject>>(json);
OrdersList = new List<RootObject>(rootObjectData);
}
public async Task<string> FetchAsync(string url)
{
string jsonString;
using (var httpClient = new System.Net.Http.HttpClient())
{
var stream = await httpClient.GetStreamAsync(url);
StreamReader reader = new StreamReader(stream);
jsonString = reader.ReadToEnd();
}
return jsonString;
}
How I need to send POST request with this json to server?
Thank's for help.
Here is an example Post request that I have used in a UWP application.
using (HttpClient httpClient = new HttpClient())
{
httpClient.BaseAddress = new Uri(#"http://test.com/");
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
httpClient.DefaultRequestHeaders.AcceptEncoding.Add(new StringWithQualityHeaderValue("utf-8"));
string endpoint = #"/api/testendpoint";
try
{
HttpContent content = new StringContent(JsonConvert.SerializeObject(yourPocoHere), Encoding.UTF8, "application/json");
HttpResponseMessage response = await httpClient.PostAsync(endpoint, content);
if (response.IsSuccessStatusCode)
{
string jsonResponse = await response.Content.ReadAsStringAsync();
//do something with json response here
}
}
catch (Exception)
{
//Could not connect to server
//Use more specific exception handling, this is just an example
}
}
You should be using httpClient.PostAsync().
I writing app for UWP
I receive json from back end like this:
string url = "http://api.simplegames.com.ua/index.php/?wc_orders=all_orders";
{
string jsonString;
using (var httpClient = new System.Net.Http.HttpClient())
{
var stream = await httpClient.GetStreamAsync(url);
StreamReader reader = new StreamReader(stream);
jsonString = reader.ReadToEnd();
}
return jsonString;
}
I try to send POST request like this
OrdersList = new List<RootObject>(rootObjectData);
using (HttpClient httpClient = new HttpClient())
{
httpClient.BaseAddress = new Uri(#"http://api.simplegames.com.ua");
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
httpClient.DefaultRequestHeaders.AcceptEncoding.Add(new StringWithQualityHeaderValue("utf-8"));
string endpoint = #"/post_from_local.php";
try
{
HttpContent content = new StringContent(JsonConvert.SerializeObject(OrdersList), Encoding.UTF8, "application/json");
HttpResponseMessage response = await httpClient.PostAsync(endpoint, content);
if (response.IsSuccessStatusCode)
{
string jsonResponse = await response.Content.ReadAsStringAsync();
Debug.WriteLine(jsonResponse);
//do something with json response here
}
}
catch (Exception)
{
//Could not connect to server
//Use more specific exception handling, this is just an example
}
}
But, Back end dev said that he see empty row, but data is not received.
Thank's for help. Where is my error?
Change this line:
var stream = await httpClient.GetStreamAsync(url);
to:
var stream = httpClient.GetStreamAsync(url).Result;
static async void DownloadData(TextBox textboxURL, TextBlock outputView)
{
try
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(textboxURL.Text);
client.Timeout = TimeSpan.FromMinutes(1);
var request = new HttpRequestMessage(HttpMethod.Get, textboxURL.Text);
/// Fixed thanks to: http://stackoverflow.com/questions/18720435/httpclient-buffer-size-limit-exceeded
HttpResponseMessage response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
/// Version = response.Version.ToString();
response.EnsureSuccessStatusCode();
// Result = await response.Content.ReadAsStringAsync();
// Task<Stream> inputStream = response.Content.ReadAsStreamAsync();
/// DUPE CODE: var sendTask = client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
/// NEED TO READ UP ON THIS: response..Result.EnsureSuccessStatusCode();
var httpStream = await response.Content.ReadAsStreamAsync();
var picker = new FileSavePicker()
{
SuggestedStartLocation = PickerLocationId.Downloads,
SuggestedFileName = "DOWNLOADING.BIN"
};
picker.FileTypeChoices.Add("Any", new List<string>() { "." });
/// picker.FileTypeChoices.Add("Any", new List<string>() { "*" });
StorageFile storageFile = await picker.PickSaveFileAsync();
// Woohoo! Got it working using await, and removing the Task<> wrapper!
using (var reader = new StreamReader(httpStream))
{
Stream fileStream = await storageFile.OpenStreamForWriteAsync();
httpStream.CopyTo(fileStream);
fileStream.Flush();
}
}
}
catch (Exception ex)
{
outputView.Text = "Error, try again!";
var dlg = new Windows.UI.Popups.MessageDialog(ex.Message, "Error");
await dlg.ShowAsync();
}
}
You're using the synchronous Stream.CopyTo method here:
httpStream.CopyTo(fileStream);
I think you just want:
await httpStream.CopyToAsync(fileStream);
However, you should also remove the StreamReader part - you're not using the StreamReader, and it's possible that it will try to read some data to detect the encoding. However, you should use a using statement for the storage file. So basically, change this:
using (var reader = new StreamReader(httpStream))
{
Stream fileStream = await storageFile.OpenStreamForWriteAsync();
httpStream.CopyTo(fileStream);
fileStream.Flush();
}
to:
using (Stream fileStream = await storageFile.OpenStreamForWriteAsync())
{
await httpStream.CopyToAsync(fileStream);
}
I have no idea how to POST JSON with HttpClient. I find some solution, like this, but I have to use HttpClient, cause of async and have to add a header.
This is my code below. Any idea how to fix it?
List<Order> list = new List<Order> { new Order() { Name = "CreatedTime", OrderBy = 1 } };
Queues items = new Queues { Orders = list };
var values = new Dictionary<string, string> { { "Orders", JsonConvert.SerializeObject(list) } };
var content = new FormUrlEncodedContent(values);
//HttpContent cc = new StringContent(JsonConvert.SerializeObject(items));
_msg = await _client.PostAsync(input, content);
//_msg = await _client.PostAsync(input, cc);
var response = await _msg.Content.ReadAsStringAsync();
You can use the method PostAsJsonAsync which can be found in the extensions assemblies:
System.Net.Http.Formatting.dll
Example
public static async Task SendJsonDemo(object content)
{
using(var client = new HttpClient())
{
var response = await client.PostAsJsonAsync("https://example.com", content);
}
}
If you want to add custom headers to the request, add it to DefaultRequestHeaders:
client.DefaultRequestHeaders.Add("mycustom", "header1");
You can send any type of request like as
public static async Task<HttpResponseMessage> SendRequest(HttpMethod method, string endPoint, string accessToken, dynamic content = null)
{
HttpResponseMessage response = null;
using (var client = new HttpClient())
{
using (var request = new HttpRequestMessage(method, endPoint))
{
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
if (content != null)
{
string c;
if (content is string)
c = content;
else
c = JsonConvert.SerializeObject(content);
request.Content = new StringContent(c, Encoding.UTF8, "application/json");
}
response = await client.SendAsync(request).ConfigureAwait(false);
}
}
return response;
}