JSON payload for HttpClient in C#? - c#

How to pass in a JSON payload for consuming a REST service.
Here is what I am trying:
var requestUrl = "http://example.org";
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualifiedHeaderValue("application/json"));
var result = client.Post(requestUrl);
var content = result.Content.ReadAsString();
dynamic value = JsonValue.Parse(content);
string msg = String.Format("{0} {1}", value.SomeTest, value.AnotherTest);
return msg;
}
How do I pass something like this as a parameter to the request?:
{"SomeProp1":"abc","AnotherProp1":"123","NextProp2":"zyx"}

I got the answer from here:
POSTing JsonObject With HttpClient From Web API
httpClient.Post(
myJsonString,
new StringContent(
myObject.ToString(),
Encoding.UTF8,
"application/json"));

Here's a similar answer showing how to post raw JSON:
Json Format data from console application to service stack
const string RemoteUrl = "http://www.servicestack.net/ServiceStack.Hello/servicestack/hello";
var httpReq = (HttpWebRequest)WebRequest.Create(RemoteUrl);
httpReq.Method = "POST";
httpReq.ContentType = httpReq.Accept = "application/json";
using (var stream = httpReq.GetRequestStream())
using (var sw = new StreamWriter(stream))
{
sw.Write("{\"Name\":\"World!\"}");
}
using (var response = httpReq.GetResponse())
using (var stream = response.GetResponseStream())
using (var reader = new StreamReader(stream))
{
Assert.That(reader.ReadToEnd(), Is.EqualTo("{\"Result\":\"Hello, World!\"}"));
}

As a strictly HTTP GET request I don't think you can post that JSON as-is - you'd need to URL-encode it and pass it as query string arguments.
What you can do though is send that JSON the content body of a POST request via the WebRequest / WebClient.
You can modify this code sample from MSDN to send your JSON payload as a string and that should do the trick:
http://msdn.microsoft.com/en-us/library/debx8sh9.aspx

Related

How to send json data in POST request using C# [duplicate]

This question already has answers here:
How to post JSON to a server using C#?
(15 answers)
Closed 5 years ago.
I want to send json data in POST request using C#.
I have tried few ways but facing lot of issues . I need to request using request body as raw json from string and json data from json file.
How can i send request using these two data forms.
Ex: For authentication request body in json --> {"Username":"myusername","Password":"pass"}
For other APIs request body should retrieved from external json file.
You can use either HttpClient or RestSharp. Since I do not know what your code is, here is an example using HttpClient:
using (var client = new HttpClient())
{
// This would be the like http://www.uber.com
client.BaseAddress = new Uri("Base Address/URL Address");
// serialize your json using newtonsoft json serializer then add it to the StringContent
var content = new StringContent(YourJson, Encoding.UTF8, "application/json")
// method address would be like api/callUber:SomePort for example
var result = await client.PostAsync("Method Address", content);
string resultContent = await result.Content.ReadAsStringAsync();
}
You can do it with HttpWebRequest:
var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://yourUrl");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = new JavaScriptSerializer().Serialize(new
{
Username = "myusername",
Password = "pass"
});
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
This works for me.
var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://url");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new
StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = new JavaScriptSerializer().Serialize(new
{
Username = "myusername",
Password = "password"
});
streamWriter.Write(json);
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}

JSON format is being returned with missing data using C# (HTTPWEBREQUEST)

I'm working with JSON and C# ( HttpWebRequest ). Basically I have application to download a JSON from and API REST, but the problem is when I download it, the JSON comes missing some data, it seems that is cutting some data, with wrong structure. If I use a software which does the same thing that I'm developing, this problem doesn't happen. I'm sure that is something with my code, if I'm missing something. Here is my code:
var httpWebRequest = (HttpWebRequest)WebRequest.Create("MyURL");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "GET";
string authInfo = "user" + ":" + "pass";
authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
httpWebRequest.Headers["Authorization"] = "Basic " + authInfo;
// Create the HttpContent for the form to be posted.
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var sr = new StreamReader(httpResponse.GetResponseStream(), Encoding.UTF8))
{
StreamWriter sw = new StreamWriter(#"C:\test\Stores.txt");
sw.Write(sr.ReadToEnd());
}
You can try this.its works in my code.
public static async Task MethodName()
{
using (HttpClientHandler handler = new HttpClientHandler() { UseCookies = false })
{
using (HttpClient httpClient = new HttpClient(handler))
{
httpClient.DefaultRequestHeaders.Authorization = Program.getAuthenticationHeader();
string filterQuery = Program.getURI().ToString();
using (HttpResponseMessage httpResponse = await httpClient.GetAsync(filterQuery).ConfigureAwait(false))
{
var streamContent = await httpResponse.Content.ReadAsStreamAsync();
FileStream fs = new FileStream("C:\test\Stores.Json", FileMode.Create);
streamContent.CopyTo(fs);
streamContent.Close();
fs.Close();
}
}
}
}
This can be an issue with your Http request (GET).
Step 1 - If you have a working software with the API, use Fiddler to analyse what is the http GET request it sends. You need to check the header info as well.
Step 2 - Compare the Http request with the HttpRequest you have created. There can be missing parameters etc.

Nutshell API authentication with C#

I'm trying to use C# to connect to the Nutshell API.
I'm unsure where the method name goes. Is it on the URL or as part of the JSON? I have tried both ways without success. I know my email is valid as I have tried the same method on the nutshell website
Here is my code:
var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://api.nutshell.com/v1/json/");
httpWebRequest.ContentType = "text/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = "{\"method\": \"getApiForUsername\", \"user\":\"myemail#email.com.au\"}";
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
What am I doing wrong?
You want your response body to look like this:
{"jsonrpc":"2.0","method":"getUser","params":[],"id": "apeye"}
For this url:
https://app01.nutshell.com/api/v1/json
TIP: use a JSON serializer to create your JSON strings

How to make HttpClient ignore Content-Length header

I am using HttpClient to communicate with a server which I don't have access to. Sometimes the JSON response from the server is truncated.
The problem occurs when the Content-Length header is smaller than what it should be (8192 vs. 8329). It seems like a bug on the server which gives a smaller Content-Length header than the actual size of the response body. If I use Google Chrome instead of HttpClient, the response is always complete.
Therefore, I want to make HttpClient to ignore the wrong Content-Length header and read to the end of the response. Is it possible to do that? Any other solution is well appreciated. Thank you!
This is the code of my HttpClient:
var client = new HttpClient();
client.BaseAddress = new Uri(c_serverBaseAddress);
HttpResponseMessage response = null;
try
{
response = await client.GetAsync(c_serverEventApiAddress + "?location=" + locationName);
}
catch (Exception e)
{
// Do something
}
var json = response.Content.ReadAsStringAsync().Result;
var obj = JsonConvert.DeserializeObject<JObject>(json); // The EXCEPTION occurs HERE!!! Because the json is truncated!
EDIT 1:
If I use HttpWebRequest, it can read to the end of the JSON response completely without any truncation. However, I would like to use HttpClient since it has better async/await.
This is the code using HttpWebRequest:
var url = c_serverBaseAddress + c_serverEventApiAddress + "?location=" + "Saskatchewan";
var request = (HttpWebRequest)WebRequest.Create(url);
request.ProtocolVersion = HttpVersion.Version10;
request.Method = "GET";
request.ContentType = "application/x-www-form-urlencoded";
var response = (HttpWebResponse)request.GetResponse();
StringBuilder stringBuilder = new StringBuilder();
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
string line;
while ((line = reader.ReadLine()) != null)
{
stringBuilder.Append(line);
}
}
var json = stringBuilder.ToString(); // COMPLETE json response everytime!!!
You could try specifying the buffer size of the response content
var client = new HttpClient();
client.MaxResponseContentBufferSize = <your_buffer_size>;
Where the property MaxResponseContentBufferSize means:
Gets or sets the maximum number of bytes to buffer when reading the response content.

HttpResponseMessage.Content.ToString(); Comes back as System.Net.Http.SteamContent

I am trying to consume an API in C#, this is the code for the request. It should be a simple JSON API, however I'm getting some irregularities here.
public static HttpResponseMessage sendRequest(List<Header> headers, string endpoint, string api_key, string api_secret)
{
using (var client = new HttpClient())
{
List<Header> headerlist = new List<Header>{};
if(headers != null)
headerlist = headers;
List<Header> signed = Helpers.sign(endpoint, api_secret);
foreach (Header header in signed)
{
headerlist.Add(header);
}
client.BaseAddress = new Uri("https://api.coinkite.com");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Add("X-CK-Key", api_key);
foreach (Header header in headerlist)
{
client.DefaultRequestHeaders.Add(header.Name, header.Data);
}
HttpResponseMessage response = client.GetAsync(endpoint).Result;
return response;
}
}
Which I am calling via
HttpResponseMessage result = Requests.sendRequest(null, "/v1/my/self", api_key, api_secret);
return result.Content.ToString();
However, when I write that to console it looks like:
System.Net.Http.SteamContent
Any clue as to what the issue is? I am not too familiar with the stream content type.
HttpContent does not implement ToString method. So you need to use result.Content.CopyToAsync(Stream) to copy the result content to a Stream.
Then you can use StreamReader to read that Stream.
Or you can use
string resultString = result.Content.ReadAsStringAsync().Result;
to read the result as string directly.This method no need to use StreamReader so I suggest this way.
Call GetResponse() on the HttpResponseMessage
Stream stream = result.GetResponseStream();
StreamReader readStream = new StreamReader(stream, Encoding.UTF8);
return readStream.ReadToEnd();
If you are only interested in the contents, you can get the string directly by changing
HttpResponseMessage response = client.GetAsync(endpoint).Result;
to
string response = client.GetStringAsync(endpoint).Result;
https://msdn.microsoft.com/en-us/library/hh551746(v=vs.118).aspx

Categories