Http post call in windows phone 8 - windows-phone-8

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);

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

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.

Windows Phone send Bitmap using multipart/form-data

My request need to look like this:
Content-Type: multipart/form-data; boundary=---BOUNDARY
-----BOUNDARY
name="receipt_photo"; filename="image_filename.jpg"
Content-Type: image/jpeg
-----BOUNDARY
I am trying to send it using following code
public async static Task addPhotosToReceipt(BitmapImage image, int idReceipt)
{
User user = PhoneApplicationService.Current.State["user"] as User;
if (user.customer.token != null)
{
RestConnector rc = new RestConnector();
byte[] data;
try
{
using (MemoryStream ms = new MemoryStream())
{
WriteableBitmap btmMap = new WriteableBitmap(image);
System.Windows.Media.Imaging.Extensions.SaveJpeg(btmMap, ms, image.PixelWidth, image.PixelHeight, 0, 100);
data = ms.ToArray();
}
string response = await rc.postAsyncData("/api/v1/receipts/" + idReceipt + "/receipt_photos/?token=" + user.customer.token, data);
if (response.Contains("error"))
{
MessageBox.Show(response);
}
}
catch (Exception ex)
{
}
}
}
//in RestConnector class
public async Task<string> postAsyncData(string adress, byte[] file)
{
using (var client = new HttpClient())
{
using (var content = new MultipartFormDataContent("---BOUNDARY"))
{
content.Add(new StringContent("-----BOUNDARY\nname=\"receipt_photo\"; filename=\"image_filename.jpg\"\nContent-Type: image/jpeg\n-----BOUNDARY"));
content.Add(new StreamContent(new MemoryStream(file)));
using (var message = await client.PostAsync(basicUrl + adress, content))
{
var input = await message.Content.ReadAsStringAsync();
return input;
}
}
}
}
In response I should get URL's to uploaded photos, but instead I got URL's to default photos. I think there is something with my request because on android it works fine.
Maybe I choosed wrong way to create byte from my bitmap?

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\" }}";

When uploading Photo to Web API always 0 bytes

I have the following, and it uploads without errors, but the image is always 0 bytes.
Windows Phone App (this is called after selecting or taking a photo):
private void AddImage(PhotoResult e)
{
if (e.TaskResult == TaskResult.OK)
{
string serviceUri = Globals.GreedURL + #"API/UploadPhoto/test5.jpg";
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(serviceUri);
request.Method = "POST";
request.BeginGetRequestStream(result =>
{
Stream requestStream = request.EndGetRequestStream(result);
e.ChosenPhoto.CopyTo(requestStream);
requestStream.Close();
request.BeginGetResponse(result2 =>
{
try
{
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(result2);
if (response.StatusCode == HttpStatusCode.Created)
{
this.Dispatcher.BeginInvoke(() =>
{
MessageBox.Show("Upload completed.");
});
}
else
{
this.Dispatcher.BeginInvoke(() =>
{
MessageBox.Show("An error occured during uploading. Please try again later.");
});
}
}
catch
{
this.Dispatcher.BeginInvoke(() =>
{
MessageBox.Show("An error occured during uploading. Please try again later.");
});
}
e.ChosenPhoto.Close();
}, null);
}, null);
}
And here is the Web API:
public class UploadPhotoController : ApiController
{
public HttpResponseMessage Post([FromUri]string filename)
{
var task = this.Request.Content.ReadAsStreamAsync();
task.Wait();
Stream requestStream = task.Result;
// Retrieve storage account from connection string.
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(ConfigurationManager.ConnectionStrings["StorageConnectionString"].ConnectionString);
// Create the blob client.
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
// Retrieve reference to a previously created container.
CloudBlobContainer container = blobClient.GetContainerReference("profilepics");
container.CreateIfNotExists();
var permissions = container.GetPermissions();
permissions.PublicAccess = BlobContainerPublicAccessType.Blob;
container.SetPermissions(permissions);
string uniqueBlobName = string.Format("test.jpg");
CloudBlockBlob blob = container.GetBlockBlobReference(uniqueBlobName);
blob.Properties.ContentType = "image\\jpeg";
blob.UploadFromStream(task.Result);
HttpResponseMessage response = new HttpResponseMessage();
response.StatusCode = HttpStatusCode.Created;
return response;
}
}
Any ideas?
Any help would be appreciated.