Rogério Silva
Rogério Silva

Reputation: 129

Windows phone app, Windows.Web.Http.HttpClient post sample

Long time searching for a sample on how to make a post call with parameters using Windows.Web.Http.HttpClient oHttpClient (that is not System.Net.Http.HttpClient !!), does some one have any? Microsoft samples never use parameters, that I could see.

Upvotes: 1

Views: 3651

Answers (2)

Rogério Silva
Rogério Silva

Reputation: 129

From yesterday, I have found how to solve this using Windows.Web.Http.HttpClient:

Windows.Web.Http.HttpClient oHttpClient = new Windows.Web.Http.HttpClient();
Uri uri= ... // some Url
string stringXml= "...";  // some xml string
HttpRequestMessage mSent = new HttpRequestMessage(HttpMethod.Post, uri);
mSent.Content = 
  new HttpStringContent(String.Format("xml={0}", stringXml), 
                        Windows.Storage.Streams.UnicodeEncoding.Utf8);

HttpResponseMessage mReceived = await oHttpClient.SendRequestAsync(mSent,
                                   HttpCompletionOption.ResponseContentRead);

// to get the xml response:
if (mReceived.IsSuccessStatusCode)
{
  string strXmlReturned await mReceived.Content.ReadAsStringAsync();
}

Upvotes: 3

LPains
LPains

Reputation: 952

I haven't done it with HtppClient but I did with WebRequest and json parameters in the request body:

WebRequest request = WebRequest.CreateHttp(url);
request.Method = "POST";
request.ContentType = "application/json";
using (var stream = await Task.Factory.FromAsync<Stream>(request.BeginGetRequestStream, request.EndGetRequestStream, null))
        {
            string postData = JsonConvert.SerializeObject(requestData);
            byte[] postDataAsBytes = Encoding.UTF8.GetBytes(postData);
            await stream.WriteAsync(postDataAsBytes, 0, postDataAsBytes.Length);
        }
using (var response = await Task.Factory.FromAsync<WebResponse>(request.BeginGetResponse, request.EndGetResponse, null))
                    {
                        return await ProcessResponse(response);
                    }

BTW, I added this code to a portable library and now I can use it on Windows Phone 8, 8.1 and Windows 8.1.

Upvotes: 0

Related Questions