Parse Json Method POST windows phone app 8.1 - json

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; */
}

Related

In Unity, using UnityWebRequest, I cant print the body of the object I want

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

How do i send additional object to client.PostAsync (along with file contents)

I have the following MVC post.
It post file contents to API.
[HttpPost]
public ActionResult FileUpload_Post()
{
if (Request.Files.Count > 0)
{
var file = Request.Files[0];
using (HttpClient client = new HttpClient())
{
using (var content = new MultipartFormDataContent())
{
byte[] fileBytes = new byte[file.InputStream.Length + 1]; file.InputStream.Read(fileBytes, 0, fileBytes.Length);
var fileContent = new ByteArrayContent(fileBytes);
fileContent.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment") { FileName = file.FileName };
content.Add(fileContent);
var result = client.PostAsync(requestUri, content).Result;
if (result.StatusCode == System.Net.HttpStatusCode.Created)
{
ViewBag.Message= "Created";
}
else
{
ViewBag.Message= "Failed";
}
}
}
}
return View();
}
What if i want to pass additional custom object (preferably json format) along with file contents?
CustomObject obj = new CustomObject;
obj.FirstName = "A";
object.LastName = "B";
Note: Following is Api method that will receive above request.
[HttpPost]
public HttpResponseMessage Upload()
{
if(!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
if (System.Web.HttpContext.Current.Request.Files.Count > 0)
{
var file = System.Web.HttpContext.Current.Request.Files[0];
....
// save the file
....
return new HttpResponseMessage(HttpStatusCode.Created);
}
else
{
return new HttpResponseMessage(HttpStatusCode.BadRequest);
}
}
First you need to serialize the CustomObject into json. e.g. using Json.NET
var jsonString = Newtonsoft.Json.JsonConvert.SerializeObject(obj);
Then you could add the jsonString to the MultipartFormDataContent like:
var jsonContent = new StringContent(jsonString);
content.Add(jsonContent, "CustomObject");
In the Upload API method, get the posted json content by
var jsonString = System.Web.HttpContext.Current.Request.Form["CustomObject"];
If the API project has a reference to class CustomObject, you could deserialize the jsonString with:
var obj = Newtonsoft.Json.JsonConvert.DeserializeObject<CustomObject>(jsonString);
If not, you could also deserialize it to a dynamic object:
var obj = Newtonsoft.Json.Linq.JObject.Parse(jsonString);

best overloaded method match for `RestSharp.Deserialize<RootObject>(RestSharp.IRestResponse)' has some invalid arguments

So i am working this project on Xamarin forms, and get the error as in title on
var rootObject = deserial.Deserialize<RootObject>(gameJson);
I am supposed to return the list of games to my app.How can i remove the error?
public async Task<Game[]> GetGamesAsync(){
var client = new RestClient("http://mystore/");
var request = new RestRequest ("api/Games", Method.GET);
request.OnBeforeDeserialization = resp => { resp.ContentType = "application/json"; };
var apiKey = session ["ApiKey"];
var userId = session ["UserId"];
try
{
request.AddHeader ("authenticationkey",apiKey.ToString ());
request.AddHeader ("authenticationid",userId.ToString ());
}
catch{}
IRestResponse response = client.Execute (request);
statusCodeCheck (response);
var gameJson = response.Content;
if (response.StatusCode == HttpStatusCode.OK) {
RestSharp.Deserializers.JsonDeserializer deserial = new RestSharp.Deserializers.JsonDeserializer ();
var rootObject = deserial.Deserialize<RootObject>(gameJson);
return rootObject.games;
}
else if(response.StatusCode == HttpStatusCode.Forbidden){
return null;
}
}
Not sure you are looking for this but I also using Restsharp in portable library and I'm deserializing datacontracts with Json.NET's JsonConvert.DeserializeObject<T>
method. I have not encountered any problem with it yet.
Also another possible solution is that the returned data is wrapped and the main object is not the RootObject.

RestClient sends null data from winphone 8 to Wcf rest service

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.

How do I send API push message with .Net / Parse.com? (C#)

This is my application code for sending push message using PARSE
public static string ParseAuthenticate(string strUserName, string
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://api.parse.com/1/push");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Headers.Add("X-Parse-Application-Id", "my app id");
httpWebRequest.Headers.Add("X-Parse-REST-API-KEY", "my rest api key");
httpWebRequest.Method = "POST";
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var responseText = streamReader.ReadToEnd();
return responseText;
}
}
Request body
{
"channels": [
"test"
],
"data": {
"alert": "12345"
}
}
Above code where is pass my request parameter(body)? how to frame my request as JSON format?
Thanks in advance.Please help me to solve this issue.
Bellow code is running for push notification using parse in .net.
private bool PushNotification(string pushMessage)
{
bool isPushMessageSend = false;
string postString = "";
string urlpath = "https://api.parse.com/1/push";
var httpWebRequest = (HttpWebRequest)WebRequest.Create(urlpath);
postString = "{ \"channels\": [ \"Trials\" ], " +
"\"data\" : {\"alert\":\"" + pushMessage + "\"}" +
"}";
httpWebRequest.ContentType = "application/json";
httpWebRequest.ContentLength = postString.Length;
httpWebRequest.Headers.Add("X-Parse-Application-Id", "My Parse App Id");
httpWebRequest.Headers.Add("X-Parse-REST-API-KEY", "My Rest API Key");
httpWebRequest.Method = "POST";
StreamWriter requestWriter = new StreamWriter(httpWebRequest.GetRequestStream());
requestWriter.Write(postString);
requestWriter.Close();
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var responseText = streamReader.ReadToEnd();
JObject jObjRes = JObject.Parse(responseText);
if (Convert.ToString(jObjRes).IndexOf("true") != -1)
{
isPushMessageSend = true;
}
}
return isPushMessageSend;
}
To send Notification to all app user you have to set the
Data field like so:
postString = "{\"data\": { \"alert\": \"Test Notification 2 From Parse Via Chinwag Admin\" },\"where\": { \"deviceType\": \"ios\" }}";