I want to convert the Object received in the function and do as needed to convert it to an object ({"some_key": "some_value"}).
Here is my code:
public HttpRequests(string url, string method, Object data)
{
//The following prepares data, according to received parameter
if (data is Array)
{
data = (Array)data;
}
else if (data is Dictionary<Object, Object>)
{
data = ((Dictionary<string, string>)data)["something"] = platform_secret;
data = ((Dictionary<string, string>)data)["something2"] = "1";
}
method = method.ToUpper(); //POST or GET
this.url = just_url + url;
this.data = Newtonsoft.Json.JsonConvert.SerializeObject(data);
this.method = method;
}
public Object performRequest()
{
if (this.data != null && url != null)
{
WebRequest request = HttpWebRequest.Create(url);
byte[] data_bytes = Encoding.ASCII.GetBytes(Convert.ToChar(data)[]);
//^ this does not work. Am I supposed to do this?
// as I said, what I want is to get an object {key: something} that can be read
// by $_POST["key"] in the server
request.Method = method;
request.ContentType = "application/x-www-form-urlencoded"; //TODO: check
//request.ContentLength = ((Dictionary<string, string>) data);
request.ContentLength = data_bytes.Length;
Stream dataStream = request.GetRequestStream(); //TODO: not async at the moment
//{BEGIN DOUBT
dataStream.Write(data_bytes, 0, data_bytes.Length);
dataStream.Close();
//DOUBT: DO THIS ^ or THIS:_ ???
StreamWriter writer = new StreamWriter(dataStream);
writer.Write(this.data);
//End DOUBT}
WebResponse response = request.GetResponse();
Stream dataResponse = response.GetResponseStream();
writer.Close();
response.Close();
dataStream.Close();
return dataResponse.
}
What exactly am I missing here?
As you initially assign this.data = Newtonsoft.Json.JsonConvert.SerializeObject(data);, suppose his.data has type string (you can change if it is otherwise).
Then instead of byte[] data_bytes = Encoding.ASCII.GetBytes(Convert.ToChar(data)[]); you need to write just byte[] data_bytes = Encoding.ASCII.GetBytes(data);
After use this
//{BEGIN DOUBT
dataStream.Write(data_bytes, 0, data_bytes.Length);
dataStream.Close();
It will help to do the call with some data but it does not help to solve your problem. request.ContentType = "application/x-www-form-urlencoded"; does not expect that the data is Newtonsoft.Json.JsonConvert.SerializeObject serialized. It expects a string containing & separated pairs that are urlencoded.
name1=value1&name2=value2&name3=value3
So, you need to use this format instead of JSON.
You need to use the first piece of code. Here is and exmaple.
But the second piece could work too, I guess. You have missed nothing on C# side. A problem could be in the data you are going to transfer, however. If it is not correctly encoded, for example.
You should be doing something closer to the lines of this...
void Main()
{
var formSerializer = new FormEncodedSerializer();
formSerializer.Add("key", "value");
formSerializer.Add("foo", "rnd");
formSerializer.Add("bar", "random");
var uri = #"http://example.com";
var contentType = #"application/x-www-form-urlencoded";
var postData = formSerializer.Serialize();
var http = new Http();
Console.WriteLine (http.Post(uri, postData, contentType));
}
public class Http
{
public string Post(string url, string data, string format)
{
var content = Encoding.UTF8.GetBytes(data);
var contentLength = content.Length;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.ServicePoint.Expect100Continue = false;
request.Method = "POST";
request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
request.ContentType = format;
request.ContentLength = contentLength;
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(content, 0, content.Length);
}
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
using (Stream responseStream = response.GetResponseStream())
using (StreamReader reader = new StreamReader(responseStream))
{
return reader.ReadToEnd();
}
}
}`
public class FormEncodedSerializer
{
private Dictionary<string, string> formKeysPairs;
public FormEncodedSerializer(): this(new Dictionary<string, string>())
{
}
public FormEncodedSerializer(Dictionary<string, string> kvp)
{
this.formKeysPairs = kvp;
}
public void Add(string key, string value)
{
formKeysPairs.Add(key, value);
}
public string Serialize()
{
return string.Join("", this.formKeysPairs.Select(f => string.Format("&{0}={1}", f.Key,f.Value))).Substring(1);
}
public void Clear()
{
this.formKeysPairs.Clear();
}
}
I did not really understand what your service expects, in which format you have to send the data.
Anyway, if you set ContentType like "application/x-www-form-urlencoded", you must encode your data with this format. You can simply do it with this code;
var values = ((Dictionary<string, string>)data).Aggregate(
new NameValueCollection(),
(seed, current) =>
{
seed.Add(current.Key, current.Value);
return seed;
});
So, your data is sent like "something=platform_secret&something2=1"
Now, you can send form data simply:
WebClient client = new WebClient();
var result = client.UploadValues(url, values);
I think your first function with signature public HttpRequests(string url, string method, Object data) dosn't seem have any logical error but in your second function with signature public Object performRequest() you have some issue:
if your HTTP method is GET you don't need to write content stream.
if your method is POST and your data are JSON you need setting up HTTP requester like this:
request.ContentType = "application/json";
and finally, flush your stream before you close it, like this request.Flush();
I'm working on project in which I'm Posting data from asp.net webform to WCF service. I'm posting data through params and the service respond me back a JSON string. Now I have an issue in deserialize. I read many threads but didn't find any solution. Hope someone can sort out my problem. Thanks in Advance
Response from WCF
{"LoginResult":false}
I just want "false" value.
How I tried:
string URL = "http://localhost:32319/ServiceEmployeeLogin.svc";
WebRequest wrGETURL;
wrGETURL = WebRequest.Create(URL+"/"+emp_username+"/"+emp_password+"/"+emp_type);
wrGETURL.Method = "POST";
wrGETURL.ContentType = #"application/json; charset=utf-8";
HttpWebResponse webresponse = wrGETURL.GetResponse() as HttpWebResponse;
Encoding enc = System.Text.Encoding.GetEncoding("utf-8");
// read response stream from response object
StreamReader loResponseStream = new StreamReader(webresponse.GetResponseStream(), enc);
// read string from stream data
strResult = loResponseStream.ReadToEnd();
var jObj = JObject.Parse(strResult);
var dict = jObj["LoginResult"].Children().Cast<JProperty>();
You could use json.net to do it like this:
public class AuthResponse {
public bool LoginResult { get; set; }
}
var deserializedResponse = JsonConvert.DeserializeObject<AuthResponse>(strResult);
http://james.newtonking.com/json
.Net 4.5 has a JavaScriptSerializer, which should work as well:
public class AuthResponse {
public bool LoginResult { get; set; }
}
System.Web.Script.Serialization.JavaScriptSerializer sr = new System.Web.Script.Serialization.JavaScriptSerializer();
AuthResponse response = sr.Deserialize<AuthResponse>(responseText);
http://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer%28v=vs.110%29.aspx
i need some help here
I am trying to make an API call by sending a json object to it.
but i am struggling to convert C# datetime to proper json format.
Here is my Sample Code.
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create("example.com");
httpWebRequest.ContentType = "text/json";
httpWebRequest.Method = "POST";
using (StreamWriter streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = "{\"ReferenceNumber\":\"Testing OAKLAND\",\"CustomerNotes\":\"Testing\",\"DeliveryDate\":" + "Date(" + System.DateTime.Now.Ticks + ")" +
",\"OrderLineItems\":[{\"ItemEntityId\":14771,\"Quantity\":2}]}";
streamWriter.Write(json);
streamWriter.Close();
}
HttpWebResponse httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (StreamReader streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
string responseText = streamReader.ReadToEnd();
Response.Write(responseText);
Response.End();
}
Please guide me how to format datetime in json and do u guys think that json this json object is fine?? I am Using .NET 2.0 Framework
Use serialization instead. It will handle any escaping and converting you need to do.
For .NET 2.0 you don't have the luxury of anonymous types, so you will have to create a model class for the data you want to serialize:
public class OrderModel {
private string _referenceNumber;
public string ReferenceNumber {
get { return _referenceNumber; }
set { _referenceNumber = value; }
}
...
class OrderItem {
private int _itemEntityId;
public int ItemEntityId {
get { return _itemEntityId; }
set { _itemEntityId; }
}
....
}
}
You can use the SerializeObject method of JSON.net
string json = JsonConvert.SerializeObject(new OrderModel {
ReferenceNumber = "Testing OAKLAND",
CustomerNotes = "Testing",
DeliveryDate = DateTime.Now,
OrderLineItems = new List<OrderItem>() {
new OrderItem { ItemEntityId = 14771, Quantity = 2 }
}
});
I know this seems like more code, but believe me it will save you a lot of hassle in the future and for any other developers looking at your code.
I'm using the code below to parse a JSON response back from the server. It's a little slow. I'm wanting to know if I should be using the JsonTextWriter as an alternative?
How would I implement this using the JsonTextWriter?
string responseString = string.Empty;
Uri uri = new Uri ("http://localhost/complex-json.json");
HttpWebRequest request = new HttpWebRequest (uri);
request.Method = "GET";
HttpWebResponse response = request.GetResponse () as HttpWebResponse;
using (StreamReader sr = new StreamReader(response.GetResponseStream())) {
responseString = sr.ReadToEnd ();
}
response.Close ();
JObject obj = JObject.Parse (responseString);
JArray a = (JArray)obj["questions"];
IList<question> questions = a.ToObject<IList<question>>();
for (int i = 0; i < a.Count; i++) {
Console.WriteLine(questions[0].answer_count);
}
System.Web.Extensions.dll has a JavaScriptSerializer. I use the following 2 extension methods to serialize and deserialize:
public static T JsonDeserialize<T>(this string json)
{
return new JavaScriptSerializer().Deserialize<T>(json);
}
public static string ToJson<T>(this T item)
{
return new JavaScriptSerializer().Serialize(item);
}
Hope this helps.
I would like to use the search method of stackoverflow API to return the json structure of results based on a search keyword and then display those results (title, description and the url) in the SearchResults div.
I am new to C# and my first attempt went something like this:
protected void searchStockOverflow(string y)
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://api.stackoverflow.com/1.1/search?intitle="+y);
httpWebRequest.ContentType = "text/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = "{ \"intitle\": \"" + y + "\"}";
streamWriter.Write(json);
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var responseText = streamReader.ReadToEnd();
SearchResults.InnerHtml += "<div style='border:1px solid blue;margin:5px;'>";
SearchResults.InnerHtml += responseText + "<br />";
SearchResults.InnerHtml += "</div><br style='clear:both;' />";
}
}
The issue is that what is returned looks like dingbats rubbish - i guess because it is serialized and need to be deserialized?
I would definitely say consider using the REST client; however, to look at the issues... generally you want to deserialize the data as JSON manually, then run that data through your UI code. For example:
static void SearchStackOverflow(string y)
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://api.stackoverflow.com/1.1/search?intitle=" + Uri.EscapeDataString(y));
httpWebRequest.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
httpWebRequest.Method = "GET";
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
string responseText;
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
responseText = streamReader.ReadToEnd();
}
var result = (SearchResult)new JavaScriptSerializer().Deserialize(responseText, typeof(SearchResult));
.... do something with result ...
}
class SearchResult
{
public List<Question> questions { get; set; }
}
class Question
{
public string title { get; set; }
public int answer_count { get; set; }
}
Which uses the JavaScriptSerializer from System.Web.Extensions.dll
Also Take a look at Stacky StackApps .Net Client Library which is REST-based API that provides access to stackoverflow family of websites.
Unfortunately I'm on my Mac and can't run a test on your code. You might want to check the character encoding of both your page and the response stream coming back. If they don't match; it could cause the characters coming from the response stream to be rendered incorrectly, hence the rubbish you're seeing.