No content when using PostAsync to post JSON - json

Using the code below, I've managed to create a jsonArray with the following format:[{"id":3},{"id":4},{"id":5}]
var jArray = new JsonArray();
int numOfChildren = 10;
for (int i = 0; i < numOfChildren; i++)
{
if (CONDITION == true)
{
var jObj = new JsonObject();
int id = SOMEID;
jObj.SetNamedValue("id", JsonValue.CreateNumberValue(id));
jArray.Add(jObj);
}
I am now trying to send "JsonArray" to a server using PostAsync as can be seen below:
Uri posturi = new Uri("http://MYURI");
HttpContent content = new StringContent(jArray.ToString(), Encoding.UTF8, "application/json");
System.Net.Http.HttpResponseMessage response = await client.PostAsync(postUri, content);
On the server side of things though, I can see that the post request contains no content. After digging around on the interwebs, it would seem that using jArray.ToString() within StringContent is the culprit, but I'm not understanding why or if that even is the problem in the first place. So, why is my content missing? Note that I'm writing this for UWP aplication that does not use JSON.net.

After much digging, I eventually Wiresharked two different applications, one with my original jArray.ToString() and another using JSON.net's JsonConver.SerializeObject(). In Wireshark, I could see that the content of the two packets was identical, so that told me that my issue resided on the server side of things. I eventually figured out that my PHP script that handled incoming POST requests was too literal and would only accept json posts of the type 'application/json'. My UWP application sent packets of the type 'application/json; charset=utf-8'. After loosening some of my content checking on the server side a bit, all was well.
For those who are looking to serialize json without the use of JSON.net, jsonArray.ToString() or jsonArray.Stringify() both work well.

You should use a Serializer to convert it to string.
Use NewtonSoft JSON Nuget.
string str = JsonConvert.SerializeObject(jArray);
HttpContent content = new StringContent(str, Encoding.UTF8, "application/json");
System.Net.Http.HttpResponseMessage response = await client.PostAsync(postUri, content);

Related

GetCapabilities Query for TileServer Returns Malformed JSON

I have installed TileServer.php. When I navigate to it, I can see my tiles (so it's working).
My issue is when I query for the getCapabilities file the resulting json file is malformed.
The json is prefixed with part of the query string at the start of the json response.
Here is the full query string:
http://<=my ip=>/tileserver/index.html?service=wmts&request=getcapabilities&version=1.0.0
Actual Json Response I Receive
(Notice wmts&request is prefixed to the otherwise valid json)
====JSON===============================
wmts&request([{"name":"190322","type":"overlay","description":"190322","version":"1.1","format":"png","bounds":[174.92249449474565,-36.991878207885335,174.93635413927785,-36.98244705946717],"maxzoom":22,"minzoom":14,"basename":"1313_190322","profile":"mercator","scale":1,"tiles": ...
==================================================
I have tried removing part of the query string to test for the results, oddly enough it grabs the part of the query string again.
Here is the full query string I tested with:
http://<=my ip=>/tileserver/index.html?request=getcapabilities&version=1.0.0
(Actual Json Response I Receive)
====JSON===============================
getcapabilities&version([{"name":"190322","type":"overlay","description":"190322","version":"1.1","format":"png","bounds":[174.92249449474565,-36.991878207885335,174.93635413927785,-36.98244705946717],"maxzoom":22,"minzoom":14,"basename":"1313_190322","profile":"mercator","scale":1,"tiles": ...
=======================================================
I could parse this out I suppose but I would like to find the cause for this issue.
I am using ASP.Net 5.0.
Here is roughly my code:
private static readonly string _tileserver_ip = "http://<my ip>/tileserver/";
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
var query = new Dictionary<string, string>
{
["service"] = "wmts",
["request"] = "getcapabilities",
["version"] = "1.0.0"
};
var response = await client.GetAsync(QueryHelpers.AddQueryString(_tileserver_ip, query));
var capabilitiesString = await response.Content.ReadAsStringAsync();
// the result of the query string => "http://<my ip>/tileserver/?service=wmts&request=getcapabilities&version=1.0.0"
EDIT
Opps! Turns out I was requesting the getCapabilities file from the TileServer in the completely wrong way.
I will leave this here encase it helps someone in the future.
Here is the correct URL: http://<= my url =>/tileserver/1.0.0/WMTSCapabilities.xml/wmts
I found the answer and I will leave this post here encase it helps someone in the future.
In my URL I was using index.html as the index page, however I should have been using index .json instead.
As soon as I switched to .json I received the JSON response as I was expecting.
Full URL with query string:
http://<=my ip=>/tileserver/index.json?service=wmts&request=getcapabilities&version=1.0.0

How to convert a stream back to json?

In a .NET 3.5 Compact Framework / Windows CE app, I need to consume some WebAPI methods that return json. RestSharp looks like it would be great for this, except that it's not quite CF-ready (see Is Uri available in some other assembly than System in .NET 3.5, or how can I resolve Uri in this RestSharp code otherwise? for details).
So, I will probably use HttpWebRequest. I can return the value from the WebAPI methods with this code:
string uri = "http://localhost:48614/api/departments";
var webRequest = (HttpWebRequest)WebRequest.Create(uri);
var webResponse = (HttpWebResponse)webRequest.GetResponse();
if ((webResponse.StatusCode == HttpStatusCode.OK) && (webResponse.ContentLength > 0))
{
StreamReader reader = new StreamReader(webResponse.GetResponseStream());
MessageBox.Show("Content is " + reader.ReadToEnd());
}
else
{
MessageBox.Show(string.Format("Status code == {0}", webResponse.StatusCode));
}
...but in order to use what's returned from reader.ReadToEnd():
...I need to convert it back to json so that I can then query the data with LINQ to JSON using either JSON.NET (http://json.codeplex.com/) or SimpleJson (http://simplejson.codeplex.com/)
Is that realistically possible (converting StreamReader data to JSON)? If so, how?
UPDATE
I'm trying to deserialize the "json" (or string that looks like json) with this code:
string uri = "http://localhost:48614/api/departments";
var webRequest = (HttpWebRequest)WebRequest.Create(uri);
webRequest.Method = "GET";
var webResponse = (HttpWebResponse)webRequest.GetResponse();
if ((webResponse.StatusCode == HttpStatusCode.OK) && (webResponse.ContentLength > 0))
{
StreamReader reader = new StreamReader(webResponse.GetResponseStream());
DataContractJsonSerializer jasonCereal = new DataContractJsonSerializer(typeof(Department));
var dept = (Department)jasonCereal.ReadObject(reader.ReadToEnd());
MessageBox.Show(string.Format("accountId is {0}, deptName is {1}", dept.AccountId, dept.DeptName));
}
...but get two err msgs on the "var dept =" line:
0) The best overloaded method match for 'System.Runtime.Serialization.XmlObjectSerializer.ReadObject(System.IO.Stream)' has some invalid arguments
1) Argument '1': cannot convert from 'string' to 'System.IO.Stream'
So reader.ReadToEnd() returns a string, and DataContractJsonSerializer.ReadObject() expects a stream, apparently. Is there a better approach for this? Or, if I'm on the right track (although currently a section of track has been removed, so to speak), how should I get past this hurdle?
UPDATE 2
I added the System.Web.Extensions reference and then "using System.Web.Script.Serialization;" but this code:
JavaScriptSerializer jss = new JavaScriptSerializer();
var dept = jss.Deserialize<Department>(s);
MessageBox.Show(string.Format("accountId is {0}, deptName is {1}",
dept.AccountId, dept.DeptName));
...but the second line fails with:
"Type 'bla+Department' is not supported for deserialization of an array."
What type should receive the call to jss.Deserialize()? How is it defined?
Well,
the ReadToEnd() method is used to read the stream into a string and output it. If you need a stream out to pass it to a method requiring a stream, you shouldn't use this method.
From what I read on this page , it seems the BaseStream property of your reader would be more appropriate to use then.

Consuming a ServiceStack service to get Raw Bytes

I'm consuming a rest service with ServiceSatck framework. Now I want to get the raw bytes.
Suppose the url is http://xx.xxx.xxx.xx/Myservice/api/hello.
In this Seeing the Http Response content in ServiceStack it seems to be using get method but I used post method.
EDIT:
I used the code
`var x = "http://xx.xxx.xxx.xx/Myservice/api/hello".PostJsonToUrl(new MyRequestDTO() { RequestData = hello }).ToArray();
I did get the raw bytes. However comparing with RestSharp method, there are about 200 bytes lost.
Using RestSharp method, the code is:
var aResponse = restClient.Execute(MyRequestDTO);
byte[] bytes = aResponse.RawBytes;
The documentation for ServiceStack's typed .NET clients shows how you can access the raw bytes:
byte[] responseBytes = client.Get<byte[]>("/poco/World");
var dto = responseBytes.FromUtf8Bytes().FromJson<PocoResponse>();
dto.Result //Hello, World
Or as a Stream:
using (Stream responseStream = client.Get<Stream>("/poco/World")) {
var dto = responseStream.ReadFully().FromUtf8Bytes().FromJson<PocoResponse>();
dto.Result //Hello, World
}
You don't even need to use the type clients for getting raw bytes, you can just as easily use a HTTP Util extension method:
byte[] rawBytes = "http://example.org/Myservice/api/hello".GetBytesFromUrl();
HOW to POST JSON and retrieve bytes using HTTP Utils extensions
var dtoBytes = new MyRequestDTO { ... }.ToJson().ToUtf8Bytes();
var responseBytes = "http://example.org/Myservice/api/hello".PostBytesToUrl(
dtoBytes, contentType:"application/json");

Netty HTTPRequest doesn't captured posted JSOn

I am attempting to build a REST service using Netty on the backend. I need to be able to post raw JSON to the service outside of any key/value parameters. Content-type=applicaiton/json not form multi-part.
I am able to get the initial part of the service to receive the request, but when I cast the MessageEvent content to HTTPRequest, it no longer has any posed data associated with it. That leaves me with no ability to get the JSON data back.
In order to access the posted JSON, do I need to use a different process for extracting the data from the MessageEvent?
Here is the snippet in question.
#Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
System.out.println("The message was received");
HttpRequest request = (HttpRequest) e.getMessage();
if (request.getMethod() != POST) {
sendError(ctx, METHOD_NOT_ALLOWED);
return;
}
// Validate that we have the correct URI and if so, then parse the incoming data.
final String path = sanitizeUri(request.getUri());
decoder = new HttpPostRequestDecoder(request);
System.out.println("We have the decoder for the request");
List<InterfaceHttpData> datas = decoder.getBodyHttpDatas();
for (InterfaceHttpData data : datas){
System.out.println(data.toString());
}
What am I missing that it causing this? Do I need to use the ChunkedWrite portion? I am a noob to Netty so forgive me if this is basic. I found lots of other questions about posting raw JSON to other URL's from inside Netty, but nothing about receiving it.
I've only used HttpPostRequestDecoder to read application/x-www-form-urlencoded or mime data.
Try just reading the data directly form the request as per the snoop example.
ChannelBuffer content = request.getContent();
if (content.readable()) {
String json = content.toString(CharsetUtil.UTF_8);
}

WebClient.DownLoadString is adding \" infront of my JSON data elements.How to parse it as normal JSON without \"?

I am trying to access a REST Service in my MVC application.I am calling getJSON method to get the data from a controller which internally calls the REST service which returns data in json format.But I am getting the a lot of "\ in my output of DownLoadString method and my return Json is not returning proper JSON data and hence my client side script is not able to access the JSON properties.
My Script in my view is
$.getJSON("#Url.Action("GetManufacturers", "Home")",function(data){
console.debug("Status is : "+data.Status)
});
My Action method looks like this
public ActionResult GetManufacturers()
{
string restURL ="http://mytestserver/myapi/Manufacturers";
using (var client = new WebClient())
{
var data = client.DownloadString(restURL);
//data variable gets "\" everywhere
return Json(data,JsonRequestBehavior.AllowGet);
}
}
I used visual studio breakpoints in my action method and i am seeing a lot of \"
And i checked what is coming out to my getJSON callback and the JSON tab is empty.
But my response tab has content like this
I belive if there is no \", i would be able to parse it nicely.
I used fiddler to see whether i am getting correct (JSON format) data from my REST service and it seems fine.
Can anyone help me to tackle this ? I would like to return proper JSON from my action method. Sometime i may want to read the json properties in the C# code itself. I saw some example of doing it with DataContractJsonSerializer. But that needs a concrete type to be converted to. I don't want to do that. because other clients would also access my RESTService and how will expect them to write a fake entity for this ?
You need to return the data as is:
public ActionResult GetManufacturers()
{
string restURL ="http://mytestserver/myapi/Manufacturers";
using (var client = new WebClient())
{
var data = client.DownloadString(restURL);
return Content(data, "application/json");
}
}