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

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:

Related

Json put/get/post in Restful webservices not working

I am trying to pass parameters to a server and extract the report in csv format. So the code i have has PUT/GET/POST in the order. I could get GET and POST work, but when i add PUT there is no error just blank screen.
String output1 = null;
URL url = new URL("http://<servername>/biprws/raylight/v1/documents/12345/parameters");
HttpURLConnection conn1 = (HttpURLConnection) url.openConnection();
conn1.setRequestMethod("PUT");
conn1.setRequestProperty("Accept", "application/json");
conn1.setRequestProperty("Content-Type", "application/json; charset=utf-8");
conn1.setDoInput(true);
conn1.setDoOutput(true);
String body = "<parameters><parameter><id>0</id><answer><values><value>EN</value></values></answer></parameter></parameters>";
int len1 = body.length();
conn1.setRequestProperty("Content-Length", Integer.toString(len1));
conn1.connect();
OutputStreamWriter out1 = new OutputStreamWriter(conn1.getOutputStream());
out1.write(body, 0, len1);
out1.flush();
What i am trying to do is pass parameter EN to the report and refresh it, take the output in csv using GET. POST is used for login to the server. I could make GET and POST work and get the output in CSV but not refreshed one.
Appreciate very much any help here.
Thanks,
Ak
What is the response code from the server when using PUT?
A PUT may not actually return a body to display on the screen; often times a PUT will only return a 200 or 204 response code. 204 would clearly mean that the server took the data and applied it, but is not sending you anything back, 200/201 may include a response, but maybe not. It depends on the folks who implemented the API.
https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html (section 9.6)
Should a RESTful 'PUT' operation return something

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.

WCF JSON returned as null

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'

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 POST JSON using Adobe Flex

I'm trying to POST some JSON data using Adobe Flex but having some problems. I'm now getting the error message "A URL must be specified with useProxy set to false", even though I do have useProxy set to false.
Update : code below is now working.
var data:Object = new Object();
data.ipaddr = ipaddr.text;
data.netmask = netmask.text;
data.gatewayip = gatewayip.text;
var jsonData:String = JSON.stringify(data);
var s:mx.rpc.http.HTTPService = new mx.rpc.http.HTTPService();
// URL needs to be specified on a separate line, call is unreliable otherwise
s.url = Utils.getBaseURL() + '/cgi-bin/setnetworksettings';
s.contentType = "application/json";
s.resultFormat = mx.rpc.http.HTTPService.RESULT_FORMAT_TEXT;
s.method = "POST";
s.useProxy = false;
s.addEventListener("result", httpResult);
s.addEventListener("fault", httpFault);
s.send(jsonData);
What do you mean by "doesn't seem to do anything"? No response from the server? Fault instead of result? Which one? Help us help you with more details, just stating it doesn't work is not enough.
First of all, be sure that your URL is correct, you should get something in the service result handler OR fault handler, anything. That should help you diagnose and fix any URL problems if any.
Then for the JSON part, you object is not a valid JSON (no escaping and : instead of =), try sending this first: {"ipaddr":"10.1.1.1"}.
From here it should be easy: as F4L stated, you can use the JSON class to encode a real object directly to JSON.
Hope that helps