I am building REST Client (c#) using windows form application in VS2017. I have been able to successfully GET and POST requests from the server using the HttpClient.PostAsJsonAsync() and ReadAsync() methods. I am trying to POST some data to the server and upon a successful POST, the server responds with a unique string like "1c77ad2e-54e0-4187-aa9d-9a55286b1f7a"
I get a successful response code (200 - OK) for the POST. However, I am not sure where to check for the resulting string. I have checked the contents of HttpResponseMessage.Content
static async Task<HttpStatusCode> PostBurstData(string path, BurstRequest
burstRequest)
{
HttpResponseMessage response = await client.PostAsJsonAsync(path, burstRequest);
response.EnsureSuccessStatusCode();
Console.WriteLine(response.Content.ToString());
// return response
return response.StatusCode;
}
The data sent to this function call is as follows:
BurstRequest request = new BurstRequest();
request.NodeSerialNumbers = SubSerialList;
request.StartTime = ((DateTimeOffset)dateTimePicker1.Value).ToUnixTimeMilliseconds();
HttpStatusCode statusCode = new HttpStatusCode();
statusCode = await PostBurstData(post_burst_url, request);
Where should I search for the string the server responds for a successful POST? Should the content be read using ReadAsync()?
if (response.IsSuccessStatusCode)
{
var data = await response.Content.ReadAsAsync();
}
Why not trying to use HttpContent like below:
using (HttpResponseMessage response = await client.GetAsync(url)) // here you can use your own implementation i.e PostAsJsonAsync
{
using (HttpContent content = response.Content)
{
string responseFromServer = await content.ReadAsStringAsync();
}
}
Related
I'm struggling with the following problem:
I've created a solution with the following projects: 1 MVC front-end and 2 test API's for testing my backend API broker.
In my front-end I call my API broker(which is also an API) which sends requests to my 2 test API's. I'm receiving the response of this request in my API Broker in string format and I'm trying to return this into JSON to my front-end, how do I consume this api and return the response in JSON to my front-end? Look code below:
Front-end calling my API Broker:
[HttpGet]
public async Task<ActionResult> getCall()
{
string url = "http://localhost:54857/";
string operation = "getClients";
using (var client = new HttpClient())
{
//get logged in userID
HttpContext context = System.Web.HttpContext.Current;
string sessionID = context.Session["userID"].ToString();
//Create request and add headers
client.BaseAddress = new Uri(url);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
//Custom header
client.DefaultRequestHeaders.Add("loggedInUser", sessionID);
//Response
HttpResponseMessage response = await client.GetAsync(operation);
if (response.IsSuccessStatusCode)
{
string jsondata = await response.Content.ReadAsStringAsync();
return Content(jsondata, "application/json");
}
return Json(1, JsonRequestBehavior.AllowGet);
}
}
My API Broker consuming one of my two test API's:
[System.Web.Http.AcceptVerbs("GET")]
[System.Web.Http.HttpGet]
[System.Web.Http.Route("RedirectApi")]
public void getCall()
{
setVariables();
WebRequest request = WebRequest.Create(apiUrl);
HttpWebResponse response = null;
response = (HttpWebResponse)request.GetResponse();
using (Stream stream = response.GetResponseStream())
{
StreamReader sr = new StreamReader(stream);
var srResult = sr.ReadToEnd();
sr.Close();
//Return JSON object here!
}
}
I'm also worried that my front-end is expecting a ActionResult instead of a JSON object, I hope you I find some suggestions here.
Thanks in advance!
use HttpClient for making the request which allows you to read the content as string. Your API needs to be configured so it will allow JSON responses (default behavior) and then here is an example of making a request and reading it as string which will be in JSON format (if the API returns a JSON body).
HttpClient client = new HttpClient();
HttpResponseMessage response = await client.GetAsync("http://www.contoso.com/");
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
Receiving JSON data back from HTTP request
I'm trying to consume data in my front-end which calls a API Broker and this API Broker calls my API. In my front-end I'm getting JSON data returned JSON with alot of backslashes in it. How can i prevent this? see code and errors below:
Consuming my API in my front-end:
[HttpGet]
public async Task<ActionResult> getCall()
{
string url = "http://localhost:54857/";
string operation = "getClients";
using (var client = new HttpClient())
{
//get logged in userID
HttpContext context = System.Web.HttpContext.Current;
string sessionID = context.Session["userID"].ToString();
//Create request and add headers
client.BaseAddress = new Uri(url);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
//Custom header
client.DefaultRequestHeaders.Add("loggedInUser", sessionID);
//Response
HttpResponseMessage response = await client.GetAsync(operation);
if (response.IsSuccessStatusCode)
{
string jsondata = await response.Content.ReadAsStringAsync();
return Content(jsondata, "application/json");
}
return Json(1, JsonRequestBehavior.AllowGet);
}
}
My Api Broker gets the request and executes this:
As you can see the response content contains alot of backslashes.
This response is going back to my front-end where i receive the following content:
In this response there are even more backslashes added.
I hope someone recognizes this problem and knows a solution.
Thanks in advance!
I fixed it by serializing the string to a JSON object and than deserialize it .
I want to be able to receive the Body content of a POST request inside the POST function definition in the REST API.
I have a client code that converts a C# object into JSON and then wraps it in a HTTP StringContent. This payload is then sent via a HTTP Post request to the URL. However the Post method in API always returns NULL when I try returning the received string.
Client:
public async void Register_Clicked(object sender, EventArgs e) // When user enters the Register button
{
Sjson = JsonConvert.SerializeObject(signup);
var httpContent = new StringContent(Sjson);
using (HttpClient client = new HttpClient())
{
client.BaseAddress = new Uri("https://apiname.azurewebsites.net");
var response = await client.PostAsync("api/values", httpContent);
var responseContent = await response.Content.ReadAsStringAsync();
StatusLabel.Text = responseContent; //To display response in client
}
}
API POST Definition:
[SwaggerOperation("Create")]
[SwaggerResponse(HttpStatusCode.Created)]
public string Post([FromBody]string signup)
{
return signup;
}
I want the clients input back as a response to be displayed in the client (StatusLabel.Text). However all I receive is NULL. Kindly guide me in the right direction.
I have prepared a simple example on how you can retrieve your Result from your Task:
async Task<string> GetResponseString(SigupModel signup)
{
Sjson = JsonConvert.SerializeObject(signup);
var httpContent = new StringContent(Sjson);
using (HttpClient client = new HttpClient())
{
client.BaseAddress = new Uri("https://apiname.azurewebsites.net");
var response = await client.PostAsync("api/values", httpContent);
var responseContent = await response.Content.ReadAsStringAsync();
}
return responseContent;
}
And you can call this as:
Task<string> result = GetResponseString(signup);
var finalResult = result.Result;
StatusLabel.Text = finalResult; //To display response in client
If you are not using async keyword, then you can call get your Result as:
var responseContent = response.Content.ReadAsStringAsync().Result;
EDIT
Basically you would have to POST your signup model to your API Controller. Use SigupModel signup as a parameter if you would like. Then whatever processing you are doing in the API, the final result in a string. Now this string can either be a null, empty or have a value. When you get this value in your client, you would have do the following:
var responseContent = await response.Content.ReadAsStringAsync();
var message = JsonConvert.DeserializeObject<string>(responseContent);
Here you will get your message a string and then you can set it as: StatusLabel.Text = message ;
I have an issue in an app developed for Windows Phone 8.1, where its working just fine, but in Windows Mobile 10 it gets stuck on GetAsync. It doesn't throw an exception or anything, just gets stuck there waiting endlessly. The content-length of the response is 22014030 bytes.
using (HttpClient client = new HttpClient())
{
using (HttpResponseMessage response = await client.GetAsync(url))
{
response.EnsureSuccessStatusCode();
using (HttpContent content = response.Content)
{
return await content.ReadAsStringAsync();
}
}
}
I have also tried reading it as a stream, but as soon as i try to read the content body nothing happens anymore.
The code that calls this function is declared as:
public async Task<List<APIJsonObject>> DownloadJsonObjectAsync()
{
string jsonObjectString = await DownloadStringAsync(Constants.URL);
if (jsonObjectString != null && jsonObjectString.Length >= 50)
{
List<APIJsonObject> result = await Task.Run<List<APIJsonObject>>(() => JsonConvert.DeserializeObject<List<APIJsonObject>>(jsonObjectString));
return result;
}
return null;
}
The reason it is blocking is because you are getting a huge response (20.9MB) which the HttpClient will try to download before giving you a result.
However, you can tell the HttpClient to return a result as soon as the response headers are read from the server, which means you get a HttpResponseMessage faster. To do this, you will need to pass HttpCompletionOption.ResponseHeadersRead as a parameter to the SendRequestAsync method of the HttpClient
Here is how:
using (var client = new HttpClient())
{
using (var request = new HttpRequestMessage(new HttpMethod("GET"), url))
{
using (var response = await client.SendRequestAsync(request, HttpCompletionOption.ResponseHeadersRead)
{
//Read the response here using a stream for example if you are downloading a file
//get the stream to download the file using: response.Content.ReadAsInputStreamAsync()
}
}
}
I'm trying to get a response from a HTTP request but i seem to be unable to. I have tried the following:
public Form1() {
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("someUrl");
string content = "someJsonString";
HttpRequestMessage sendRequest = new HttpRequestMessage(HttpMethod.Post, client.BaseAddress);
sendRequest.Content = new StringContent(content,
Encoding.UTF8,
"application/json");
Send message with:
...
client.SendAsync(sendRequest).ContinueWith(responseTask =>
{
Console.WriteLine("Response: {0}", responseTask.Result);
});
} // end public Form1()
With this code, i get back the status code and some header info, but i do not get back the response itself. I have tried also:
HttpResponseMessage response = await client.SendAsync(sendRequest);
but I'm then told to create a async method like the following to make it work
private async Task<string> send(HttpClient client, HttpRequestMessage msg)
{
HttpResponseMessage response = await client.SendAsync(msg);
string rep = await response.Content.ReadAsStringAsync();
}
Is this the preferred way to send a 'HttpRequest', obtain and print the response? I'm unsure what method is the right one.
here is a way to use HttpClient, and this should read the response of the request, in case the request return status 200, (the request is not BadRequest or NotAuthorized)
string url = 'your url here';
// usually you create on HttpClient per Application (it is the best practice)
HttpClient client = new HttpClient();
using (HttpResponseMessage response = client.GetAsync(url).GetAwaiter().GetResult())
{
using (HttpContent content = response.Content)
{
var json = content.ReadAsStringAsync().GetAwaiter().GetResult();
}
}
and for full details and to see how to use async/await with HttpClient you could read the details of this answer