I want to know the best way to send a small json string/ data to a web service. I can use WebClient or httpwebrequest that's not the issue, but i am mainly concerned about how to convert the string into json format and post with the request.
As suggested , here i am using json.net , following is the code :
Uri url = new Uri("http://example.com");
//Create the web request object
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.Method = "POST";
webRequest.ContentType = "application/json";
// Start the request
webRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), webRequest);
void GetRequestStreamCallback(IAsyncResult asynchronousResult)
{
HttpWebRequest webRequest = (HttpWebRequest)asynchronousResult.AsyncState;
// End the stream request operation
Stream postStream = webRequest.EndGetRequestStream(asynchronousResult);
//
JObject json =
new JObject(
new JProperty("customer", new JObject
(
new JProperty("phoneNumber", "07700555555"),
new JProperty("name", "John")
))
,
new JProperty("pickupAddress", new JObject
(
new JProperty("street", "1 Seagull Lane"),
new JProperty("city", "London"),
new JProperty("county", "London"),
new JProperty("postcode", "E000XX"),
new JProperty("country", "England"),
new JProperty("longitude", "10.18"),
new JProperty("latitude", "12.214")
))
,
new JProperty("destinationAddress", new JObject
(
new JProperty("county", "London"),
new JProperty("street", "1 Snow Lane"),
new JProperty("longitude", "1.79"),
new JProperty("latitude", "1.294"),
new JProperty("postcode", "E00XX"),
new JProperty("country", "England"),
new JProperty("city", "London")
))
,
new JProperty("pickupTime", "1311467121460"),
new JProperty("notes", "some notes"),
new JProperty("accountNumber", "account1"),
new JProperty("accountPassword", "account password")
);
//
// Create the post data
// Demo POST data
//byte[] byteArray = Encoding.UTF8.GetBytes(json.ToString());
//byte[] byteArray = Encoding.UTF8.GetBytes("1233456");
//
JsonSerializer serializer = new JsonSerializer();
serializer.NullValueHandling = NullValueHandling.Ignore;
using (StreamWriter sw = new StreamWriter(postStream))
using (JsonWriter writer = new JsonTextWriter(sw))
{
//serializer.Serialize(writer, JsonConvert.SerializeObject(json));
json.WriteTo(writer,null);
}
//
// Add the post data to the web request
//postStream.Write(byteArray, 0, byteArray.Length);
postStream.Close();
// Start the web request
webRequest.BeginGetResponse(new AsyncCallback(GetResponseCallback), webRequest);
}
void GetResponseCallback(IAsyncResult asynchronousResult)
{
try
{
HttpWebRequest webRequest = (HttpWebRequest)asynchronousResult.AsyncState;
HttpWebResponse response;
// End the get response operation
response = (HttpWebResponse)webRequest.EndGetResponse(asynchronousResult);
Stream streamResponse = response.GetResponseStream();
StreamReader streamReader = new StreamReader(streamResponse);
var Response = streamReader.ReadToEnd();
MessageBox.Show(Response);
streamResponse.Close();
streamReader.Close();
response.Close();
}
catch (WebException e)
{
// Error treatment
// ...
}
}
Now the code seems to be ok , json data is created ok , but response from server is showing : "the server response e = {"The remote server returned an error: NotFound."}"
I don't know what's going wrong , please help friends ! Some one told me that i have to add something in header of the request i.e. The header should show: booking = {...JSON...}
You could use the built in DataContractJsonSerializer Class.
Alternatively, you may get better performance with json.net.
Related
I used to do a post request using native C#'s library
var httpWebRequest = (HttpWebRequest)WebRequest.Create(djangoApi + user);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = "{\"wallet_id\":\""+wallet+"\"," +
"\"token\":\"foo\"}";
streamWriter.Write(json);
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
but that doesn't work on mobile. So, I need to use UnityWebRequest
Following the example, https://docs.unity3d.com/Manual/UnityWebRequest-SendingForm.html, my functions look almost identical. Here is the coroutine function
IEnumerator SendPostCoroutine()
{
WWWForm form = new WWWForm();
form.AddField("user_id", "0x241477cE189fa014292d99e0807cB449b878");
form.AddField("token", "foo");
using (UnityWebRequest www = UnityWebRequest.Post(djangoApi + user, form))
{
Debug.Log(www.downloadHandler.text);
yield return www.SendWebRequest();
if (www.isNetworkError)
{
Debug.Log(www.error);
}
else
{
Debug.Log("POST successful!");
StringBuilder sb = new StringBuilder();
foreach (KeyValuePair<string, string> dict in www.GetResponseHeaders())
{
sb.Append(dict.Key).Append(": \t[").Append(dict.Value).Append("]\n");
}
// Print Headers
Debug.Log(sb.ToString());
string response = Encoding.UTF8.GetString(www.downloadHandler.data);
Debug.Log(response);
Debug.Log(www.downloadHandler.text);
}
}
}
When I do
string response = Encoding.UTF8.GetString(www.downloadHandler.data);
Debug.Log(response);
Debug.Log(www.downloadHandler.text);
neither prints out the body of the object I want. Instead, all I get is
<!DOCTYPE html>
<html lang="en">
What can I do to get the values within the json?
I just used
IEnumerator Post(string url, string bodyJsonString)
{
var request = new UnityWebRequest(url, "POST");
byte[] bodyRaw = Encoding.UTF8.GetBytes(bodyJsonString);
request.uploadHandler = (UploadHandler) new UploadHandlerRaw(bodyRaw);
request.downloadHandler = (DownloadHandler) new DownloadHandlerBuffer();
request.SetRequestHeader("Content-Type", "application/json");
yield return request.Send();
Debug.Log("Status Code: " + request.responseCode);
}
taken from https://forum.unity.com/threads/posting-json-through-unitywebrequest.476254/. That way, I can post my raw json
I am working on c# utility to migrate data from SQL server 2017 to MongoDB. Below are steps I am following
1) Getting data from SQL server in JSON format (FOR JSON AUTO)
2) Parsing into BSON document
3) Then trying to insert into MongoDB
But I am getting error while reading JSON data from SQL.
My Json data is combination of root attributes as well as nested objects.
So Its dynamic data, that I want to PUSH as it is to MongoDB.
string jsonData = string.Empty;
foreach (var userId in userIdList)
{
using (SqlConnection con = new SqlConnection("Data Source=;Initial Catalog=;Integrated Security=True"))
{
using (SqlCommand cmd = new SqlCommand("Usp_GetUserdata", con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#userId", SqlDbType.Int).Value = userId;
con.Open();
var reader = cmd.ExecuteReader();
jsonResult = new StringBuilder();
//cmd.ExecuteNonQuery();
if (!reader.HasRows)
{
jsonResult.Append("[]");
}
else
{
while (reader.Read())
{
jsonResult.Append(reader.GetValue(0));
jsonData = reader.GetValue(0).ToString();
File.WriteAllText(#"c:\a.txt", jsonResult.ToString());
File.WriteAllText(#"c:\a.txt",jsonData);
jsonData.TrimEnd(']');
jsonData.TrimStart('[');
//Create client connection to our MongoDB database
var client = new MongoClient(MongoDBConnectionString);
//Create a session object that is used when leveraging transactions
var session = client.StartSession();
//Create the collection object that represents the "products" collection
var employeeCollection = session.Client.GetDatabase("mongodev").GetCollection<BsonDocument>("EmpData");
//Begin transaction
session.StartTransaction();
try
{
dynamic resultJson = JsonConvert.DeserializeObject(result);
var document = BsonSerializer.Deserialize<BsonDocument>(resultJson);
//MongoDB.Bson.BsonDocument document
// = MongoDB.Bson.Serialization.BsonSerializer.Deserialize<BsonDocument>(jsonResult);
employeeCollection.InsertOneAsync(document);
//BsonArray pipeline =
// MongoDB.Bson.Serialization.BsonSerializer.Deserialize<BsonArray>(jsonData);
//var documents = pipeline.Select(val => val.AsBsonDocument);
//employeeCollection.InsertManyAsync(documents);
session.CommitTransaction();
}
catch (Exception e)
{
Console.WriteLine(e);
session.AbortTransaction();
throw;
}
}
}
}
}
}
I've down Method GET with HttpClient, but i dont know how to get data with param (id) or by method POST, anyone help me.
this is a code GET with HttpClient i use before, hope method POST same it.
public async void getreponse()
{
var postrequest = (HttpWebRequest)WebRequest.Create("http://210.86.239.156/PIXA/app_truyenhay/api/list_story");
postrequest.Method = "GET";
postrequest.CookieContainer = new CookieContainer();
HttpWebResponse postresponse = (HttpWebResponse)await postrequest.GetResponseAsync();
string response = String.Empty;
if (postresponse != null)
{
var postResponseStream = postresponse.GetResponseStream();
var postStreamReader = new StreamReader(postResponseStream);
response = await postStreamReader.ReadToEndAsync();
}
ListStory liststory = Newtonsoft.Json.JsonConvert.DeserializeObject<ListStory>(response);
/*foreach (var blog in liststory.items)
blog.storyImage = "http://a.wattpad.com/cover/30539421-256-k910647.jpg";
//LBTruyen.ItemsSource = liststory.items; */
}
I'm new to windows phone 8 development.
Could you please help me how to send the xml data to the server through http post calls in windows phone 8?
Thanks
This is a sample code I used in my project. Modify according to your needs
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("url to submit to");
req.Method = "POST";
//Add a Header something like this
//req.Headers["SOAPAction"] = "http://asp.net/ApplicationServices/v200/AuthenticationService/Login";
req.ContentType = "text/xml; charset=utf-8";
//req.UserAgent = "PHP-SOAP/5.2.6";
string xmlData = #"<?xml version=""1.0"" encoding=""UTF-8""?>Your xml data";
// Convert the string into a byte array.
byte[] byteArray = Encoding.UTF8.GetBytes(xmlData);
req.Headers[HttpRequestHeader.ContentLength] = byteArray.Length.ToString();
req.BeginGetRequestStream(ar =>
{
using (var requestStream = req.EndGetRequestStream(ar))
{
// Write the body of your request here
requestStream.Write(byteArray, 0, xmlData.Length);
}
req.BeginGetResponse(a =>
{
try
{
var response = req.EndGetResponse(a);
var responseStream = response.GetResponseStream();
using (var streamRead = new StreamReader(responseStream))
{
// Parse the response message here
string responseString = streamRead.ReadToEnd();
//If response is also XML document, parse it like this
XDocument xdoc = XDocument.Parse(responseString);
string result = xdoc.Root.Value;
if (result == "true")
{
//Do something here
}
else
Dispatcher.BeginInvoke(() =>
{
//result failed
MessageBox.Show("Some error msg");
});
}
}
catch (Exception ex)
{
Dispatcher.BeginInvoke(() =>
{
//if any unexpected exception occurs, show the exception message
MessageBox.Show(ex.Message);
});
}
}, null);
}, null);
string URL="https://sampleservicebus.servicebus.windows.net/WinPhoneService/"
RestClient client = new RestClient(URL);
RestRequest request = new RestRequest("getkpimeasuredata", Method.POST);
KpiDomainData kpidata = new KpiDomainData();
kpidata.KPIId = 1006;
kpidata.ScorecardId = 3;
kpidata.EngineeringOrgId = 11;
kpidata.DataValuetypeId = 1;
kpidata.CumulativeMonth = 463;
kpidata.BusinessOrgId = 1;
string json = Newtonsoft.Json.JsonConvert.SerializeObject(kpidata);
json = "{\"kpidata\" : " + json + "}";
request.AddParameter("application/json; charset=utf-8", json, ParameterType.RequestBody);
request.RequestFormat = DataFormat.Json;
ObservableCollection<KpiMeasureData> kpiDetailsList = await client.ExecuteTaskAsync<ObservableCollection<KpiMeasureData>>(request);
client.ExecuteAsync(request, response =>
{
if (response.StatusCode == HttpStatusCode.OK)
{
}
});
When I debugged the wcf service code i came to know that the json data sent to getkpimeasuredata webmethod is null, I mean all the property values of the composite type were null even though I'm passing the data with values
And the Restcall works when I use Webclient instead of Restclient. But I need to use Restclient only. Please help.