WCF JSON returned as null - json

Following this tutorial: I have created a WP8 Mobile Application and trying to call my WCF web service. When calling the WCF service in the browser, I can see the JSON returned with no problems at all. However, when I call the WCF service in my mobile application, I don't get anything back. I have no clue where I am going wrong.
This is the code that call the WCF:
string ServiceUri = "urlgoeshere";
WebClient proxy = new WebClient();
proxy.DownloadStringCompleted += new DownloadStringCompletedEventHandler(proxy_DownloadStringCompleted);
proxy.DownloadStringAsync(new Uri(ServiceUri));
And the event handler:
Stream stream = new MemoryStream(Encoding.Unicode.GetBytes(e.Result));
DataContractJsonSerializer obj = new DataContractJsonSerializer(typeof(List<SightingType>));
var result = obj.ReadObject(stream) as List<SightingType>;
What am I doing wrong? I've obviously changed the ServiceUri to "urlgoeshere" but rest assured, the actual URL works perfectly, 100% A-OK when I run it in my browser. When running it in this mobile app however, it doesn't work. Can anyone see the obvious problem?
Update
If I do:
var result = obj.ReadObject(stream);, and if I step into stream, I can see a:
ReadTimeout = 'stream.ReadTimeout' threw an exception of type 'System.InvalidOperationException'

Related

Spring WebClient not processing JSON content

I have an app that uses WebClient to fetch JSON data from ComicVine as follows:
WebClient client = WebClient.builder()
.baseUrl(url)
.defaultHeaders(
headers -> {
headers.add(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE);
headers.add(HttpHeaders.USER_AGENT, "ComiXed/0.7");
})
.build();
Mono<ComicVineIssuesQueryResponse> request =
client
.get()
.uri(url)
.accept(MediaType.APPLICATION_JSON)
.retrieve()
.bodyToMono(ComicVineIssuesQueryResponse.class);
ComicVineIssuesQueryResponse response = request.block();
For a time this worked. But then, all of a sudden, it's throwing the following root exception when it executes:
Caused by: org.springframework.web.reactive.function.UnsupportedMediaTypeException: Content type 'application/json' not supported for bodyType=org.comixed.scrapers.comicvine.model.ComicVineIssuesQueryResponse
at org.springframework.web.reactive.function.BodyExtractors.lambda$readWithMessageReaders$12(BodyExtractors.java:201)
I'm not sure why it all of a sudden won't process JSON data. My unit test, which is explicitly returning JSON data and setting the content type properly:
private MockWebServer comicVineServer;
this.comicVineServer.enqueue(
new MockResponse()
.setBody(TEST_GOOD_BODY)
.addHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE));
Any ideas why this is the case? It's happening across multiple classes that use this same setup for WebClient and for testing.
After doing some digging, I added the following code to get the JSON as a String and then use ObjectMapper to convert it to the target type:
Mono<String> request =
client
.get()
.uri(url)
.accept(MediaType.APPLICATION_JSON)
.retrieve()
.bodyToMono(String.class);
String value = request.block();
ObjectMapper mapper = new ObjectMapper();
ComicVineIssuesQueryResponse response = mapper.readValue(value, ComicVineIssuesQueryResponse.class);
This quickly exposed the underlying problem, which was that two instance variables in the response were annotated with the same JSON field name. Once I fixed that, things started working correctly again.
you can parse the json content to string without calling block method.
option 1) Jackson2Tokenizer
option 2) put your code which is calling "objectMapper.readValue(..) .." inside map operator.

WCF GET returning XML instead of JSON on server

I have a WCF service with a webHttpBinding defined. The interface has a single method:
[OperationContract(Action = "*")]
[WebGet(UriTemplate = "/",RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
Stream GetServerInfo();
Which returns a stream with encoded JSON:
WebOperationContext.Current.OutgoingResponse.Headers.Add("Access-Control-Allow-Origin", "*");
ServerData r = ServerData.Instance;
r.upTime = (DateTime.Now - r._startupTime).ToString(#"dd\.hh\:mm\:ss");
using (Process proc = Process.GetCurrentProcess())
{
r.usedMemory = ((double)proc.PrivateMemorySize64) / 1024 / 1024;
}
r.activeSessions = getServiceData().Count();
string jsCode = "displayData" + "("+
new JavaScriptSerializer().Serialize(r)
+")";
WebOperationContext.Current.OutgoingResponse.ContentType = "application/javascript";
Console.WriteLine(jsCode);
return new MemoryStream(Encoding.UTF8.GetBytes(jsCode));
When used on my devel PC it works fine. I get sth like:
displayData({"_startupTime":"\/Date(1435867525056)\/","serverVersion":"1.0.0.8","startUpTime":"2. 7. 2015 22:05:25","acceptedConnections":0,"upTime":"00.00:00:00","usedMemory":21.265625,"activeSessions":0})
However, after deploy to a remote server I get only following response and I want to get a JSON:
<GetServerInfoResponse xmlns="http://tempuri.org/"><GetServerInfoResult>ZGlzcGxheURhdGEoeyJfc3RhcnR1cFRpbWUiOiJcL0RhdGUoMTQzNTg2ODUwMjc5NClcLyIsInNlcnZlclZlcnNpb24iOiIxLjAuMC44Iiwic3RhcnRVcFRpbWUiOiI3LzIvMjAxNSAxOjIxOjQyIFBNIiwiYWNjZXB0ZWRDb25uZWN0aW9ucyI6MCwidXBUaW1lIjoiMDAuMDA6MDA6MDAiLCJ1c2VkTWVtb3J5IjoyNy40NzY1NjI1LCJhY3RpdmVTZXNzaW9ucyI6MH0p</GetServerInfoResult></GetServerInfoResponse>
Note I call for the request locally directly on the server. But on remote call over network the response is the same. If I put a log output of the string to console I can see the output string is correct.
The config files are identical (except for addresses).
--edit
With the try-fail method I found out the string inside the XML response is the JSON string encoded in Base64.
Can somebody please help me whats wrong?
After some research I did not find any solution. However, after restarting OS (Win Server 2012) and rebuilding it just works like a charm.

Json: the remote server returned an error (500) internal server error

i am trying to read a web service in Json format
here is my code:
WebClient wc = new WebClient();
wc.UseDefaultCredentials = true;
var data = wc.DownloadString(JsonUri);
MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(data));
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(List<PaymentMethod>));
var result = serializer.ReadObject(ms);
ms.Close();
ms.Dispose();
i get an error on this line:
var data = wc.DownloadString(JsonUri);
the JsonUri is : http://avaris.kwekud.com/api/v1/items/uniqueitem/?username=joel&api_key=959dd41efd06b84ca7f10b1b12f5f3e6567c07dc&format=json
Any Help
thanks
It looks like there is a problem in the python code on the server that is returning the API. A good idea is to try to make the call from outside of your code to make sure that it is not your code. Any packet sniffing tool eg firebug in firefox will be able to tell you if the call is going wrong pr its your code being badly formed.
It looks like the API is currently broken, so you should put a try ... catch in there and handle the exception for situations like this:

Consuming a post method in WCF REST template 40 - JSON

am getting rather frustrated at the lack of information out there on how to post data to a WCF REST method in JSON form. I have tried almost everything out there. Google is just returning purple links at this point...
What I am looking for is a way to send a JSON object to my method so it can shelve all of the data for me. What I am currently trying to get working is below:
The Method header:
[WebInvoke(Method = "POST", UriTemplate = "role/new", ResponseFormat = WebMessageFormat.Json)]
void AddNewRole(Stream streamdata)
The logic from the client app:
string json = JsonConvert.SerializeObject(role);
byte[] buffer = Encoding.UTF8.GetBytes(json);
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("https://IP/InfoService/role/new");
request.Method = "POST";
request.Credentials = new NetworkCredential("", "");
request.ContentType = "application/x-www-form-urlencoded";
using (StreamWriter sw = new StreamWriter(request.GetRequestStream()))
{
sw.Write(json);
}
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (StreamReader sr = new StreamReader(response.GetResponseStream()))
{
MessageBox.Show(sr.ReadToEnd());
}
Using this method I get an accepted response from the service, but it is a blank response and no new data gets added to the database. Granted, it is possible that there is a problem with my database update methods. Either way, can anyone help me figure out where I am going wrong?
EDIT: I now have fiddler able to test on the test client, and as expected there are problems with my DB queries. Ill post back soon.
EDIT2: Finally worked out the database problems, I have now successfully invoked through fiddler.
EDIT3: Its working now, thanks to nobody.
The code above has been edited, it works.

How to get JSON from a WCF Data Services, DataServiceQuery call in Silverlight?

Background: I have a WCF Data Service with a Silverlight application that is currently using atom pub xml. I want to use JSON to lessen the size of the payload.
I read that you can JSON from the service webget using the following code:
WebClient wc = new WebClient();
wc.Headers["Accept"] = "application/json";
Can I modify the header for a DataServiceQuery call or a localContext.BeginExecute (for WebGets)?
// WCF Data Services Query Proxy
DataServiceQuery<T> query = filterExpression as DataServiceQuery<T>;
// Execute the ASYNC query against the model
query.BeginExecute(new AsyncCallback((iar) =>
{ ...});
or
// Create new context with the WCF service to force only save this entity
VisiconnEDM localContext = new VisiconnEDM(new Uri(entityServiceURL, UriKind.Absolute));
// execute the query asynchronously
localContext.BeginExecute<T>(urlQuery,(IAsyncResult iar) =>{ ...},null);
Even if you would modify the header for DataServiceRequest the client library of WCF DS doesn't have support for reading JSON responses, so it would not be able to read the response. The currently suggested approach to decrease the payload size is to use GZip.