1

I would like to send POST request in windows phone 8 environment my code is running successfully but i am getting NotFound exception. Its mean is i want to POST some data but i am sending null. So please let me know how to send POST Request asynchronously with Data in windows phone 8 environmet. I tried following links but not helpful. link link2

I approached like this

private async Task<LastRead> SyncLastReadPOST(LastRead lastreads, bool actionStatus)
{
    string jsondata = "";
    actionStatus = false;
    apiData = new LastReadAPI()//It is global variable from apiData this object has the information
    {
        AccessToken = thisApp.currentUser.AccessToken,
        Book = lastreads.Book,
        Page = lastreads.Page,
        Device = lastreads.Device
    };
    jsondata = Newtonsoft.Json.JsonConvert.SerializeObject(apiData);
    LastRead responsedData = new LastRead();
    Uri lastread_url = new Uri(string.Format("{0}lastread", url_rootPath));
    try
    {
        HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(lastread_url);
        webRequest.ContentType = "application/json";
        webRequest.Accept = "application/json;odata=verbose";
        webRequest.Method = "POST";
        webRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), webRequest);
    }
    catch { }
    return responsedData;
}

private void GetRequestStreamCallback(IAsyncResult ar)
{
    HttpWebRequest request = (HttpWebRequest)ar.AsyncState;
    Stream postStream = request.EndGetRequestStream(ar);
    var input = Newtonsoft.Json.JsonConvert.SerializeObject(jsondata);//jsondata is my global data variable in json format.
    byte[] byteArray = Encoding.UTF8.GetBytes(input);
    postStream.WriteAsync(byteArray, 0, byteArray.Length);
    postStream.Close();
    request.BeginGetResponse(new AsyncCallback(GetResponseStreamCallback), request);
}

private void GetResponseStreamCallback(IAsyncResult ar)
{
    try
    {
        HttpWebRequest webRequest = (HttpWebRequest)ar.AsyncState;
        HttpWebResponse response;
        //In following line i am getting the exception notFound.
        response = (HttpWebResponse)webRequest.EndGetResponse(ar);
        Stream streamResponse = response.GetResponseStream();
        StreamReader streamReaders = new StreamReader(streamResponse);
        var responces = streamReaders.ReadToEnd();
        streamResponse.Close();
        streamReaders.Close();
        response.Close();
    }
    catch(Exception ex)
    {
    }
}

As far as i know notFound exceptions comes when we are not posting any data while using the POST request method. you can see i have mentioned the data i am passing into the GEtRequestStreamCallback. I have mentioned a note. Please help me. Where i am going to wrong.

Community
  • 1
  • 1
Ashish-BeJovial
  • 1,829
  • 3
  • 38
  • 62
  • Have you tried POSTing the API in a HTTPposter like HttpRequester in firefox – Jagath Murali Feb 05 '14 at 11:59
  • You are right at your point. But code must run first than i can do such stuff. – Ashish-BeJovial Feb 05 '14 at 12:44
  • share code snippet if possible, also let us know the execution environment(trying to POST from emulator/device to local hosted/live web API)? – gitesh.tyagi Feb 05 '14 at 14:09
  • Executing on windows phone 8 emulator, i update my question too with the code. – Ashish-BeJovial Feb 05 '14 at 14:15
  • @gitesh.tyagi I have updated my code now. Please have a look. Where i am going wrong? pls suggest. – Ashish-BeJovial Feb 06 '14 at 06:59
  • @AshishJain although you are explicitly encoding the content in UTF-8(which is default) try setting the content-type to application/json; charset=utf-8 – gitesh.tyagi Feb 06 '14 at 17:55
  • @AshishJain, the `async` keyword doesn't magically make your code asynchronous. You must be getting a warning about the missing `await`. – Paulo Morgado Feb 07 '14 at 00:12
  • @AshishJain, have you looked at the [HttpClient Class](http://msdn.microsoft.com/library/system.net.http.httpclient.aspx)? You can get it from the [Microsoft HTTP Client Libraries](https://www.nuget.org/packages/Microsoft.Net.Http) **NuGet** package. Although the `WebClient` supports Task-Based asynchronous programming (see the **TaskAsync** suffixed methods), the `HttpClient` is better suited for asynchronous programming. – Paulo Morgado Feb 07 '14 at 00:19

2 Answers2

1

Try setting the content-type to application/json; charset=utf-8

Also, you can do all that stuff in nicer and shorter way(sample):

var wc = new WebClient();
//SET AUTH HEADER IF NECESSARY
//wc.Headers["Authorization"] = "OAUTH "+TOKEN; 
wc.Headers["Content-Type"] = "application/json;charset=utf-8";
wc.UploadStringCompleted += (s, er) =>
{
   if (er.Error != null) MessageBox.Show("Error\n" + er.Error);
   else MessageBox.Show(er.Result);
};
string data = JsonConvert.SerializeObject(MY_DATA_OBJECT);
MessageBox.Show(data);
wc.UploadStringAsync(new Uri(POST_URI), "POST", data);
gitesh.tyagi
  • 2,271
  • 1
  • 14
  • 21
  • Gitesh Superb logic you used. But is it possible to trace the response ? Becasause i want to make a object from the response and that response i will use where from i am calling UploadPOST_Data(myWrapperClass object) function. – Ashish-BeJovial Feb 07 '14 at 06:33
  • I am using above approach and it seems it will work, but i dont know how can i fetch the response from this approach so i can not confirm it is working. – Ashish-BeJovial Feb 07 '14 at 06:36
  • @AshishJain er.Result is actually [UploadStringCompletedEventArgs.Result](http://msdn.microsoft.com/en-us/library/system.net.uploadstringcompletedeventargs.result(v=vs.110).aspx) Property which contains server response.(Side Note: You should check the Error and Cancelled properties to determine whether the upload completed) – gitesh.tyagi Feb 07 '14 at 08:40
0

I did it with the help of HttpClient inplace of WebClient. Following few lines will do magic. :)

HttpClient hc = new HttpClient();
hc.BaseAddress = new Uri(annotation_url.ToString());
HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Post, myUrl);
HttpContent myContent = req.Content = new StringContent(myJsonString, Encoding.UTF8, "application/json");
var response = await hc.PostAsync(myUrl, myContent);

//Line for pull out the value of content key value which has the actual resposne.
string resutlContetnt = response.Content.ReadAsStringAsync().Result;
DataContractJsonSerializer deserializer_Json = new DataContractJsonSerializer(typeof(MyWrapperClass));
MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(resutlContetnt.ToString()));
AnnotateResponse = deserializer_Json.ReadObject(ms) as MyWrapperClass;
Ashish-BeJovial
  • 1,829
  • 3
  • 38
  • 62