Forum General

HttpClient POST

mcormcor USMember ✭✭

Hi,

    Scenario:
             I can access or retrieve data from WCF (GET) and it works good.  And it called from the client side (That's the code below).

    Problem:
             1.) How to make a Method POST on the WCF side with a parameters to receive a value from client ?
             2.) How to call it from the client side (base on code below) using HTTP Client with a parameters to pass  thru WCF POST ? 

   Please help...

//WCF Side

[ServiceContract]
public interface IHttpService
{
[OperationContract]
[WebInvoke(Method="GET",ResponseFormat=WebMessageFormat.Xml,BodyStyle=WebMessageBodyStyle.Bare,UriTemplate="GetListData/{sqlProc}")]
string GetListData(string sqlProc);

}

public class HttpService : IHttpService
{
public string GetData(string value)
{
return string.Format("You entered: {0}", value);
}
}

//CLIENT SIDE

           string paramData = "Hello World";
         string paramlocal = string.Format("http://localhost:50378/HttpService.svc/{0}/{1}", "GetData", paramData);


         HttpClient client = new HttpClient();
         HttpResponseMessage wcfResponse = client.GetAsync(paramlocal).Result;
         HttpContent stream = wcfResponse.Content;
         var data = stream.ReadAsStringAsync();
         string result = data.Result.ToString();

Best Answer

Answers

  • EidandEidand GBMember, University ✭✭✭

    this looks like a restful wcf.

    Have a look at one of my articles, it shows how to work with the HttpClient in a mobile context ( PCL ) and it does all kinds of things: get, post, authentication etc. Ignore the authentication stuff just go for the main usage.

    Here is the link:
    http://eidand.com/2015/04/22/xamarin-ios-authentication-using-owin-web-api2-json-web-tokens/

    The code is available on Github for your perusing pleasure and the link is inside the article.

    Good luck and let me know if it helps at all.

  • mcormcor USMember ✭✭

    Hi Andrei,

       I'm checking this  code https://eidand.files.wordpress.com/2015/04/validateuser.jpg.
    
       using (var client = new HttpClient())
       {
              var formContent = new FormUrlEncodedContent (new []
               {
                       new KeyValuePair<string,string>("Username", loginModel.UserName),
                       new KeyValuePair<string,string>("Password",loginModel.Password)
               });
    
               client.DefaultRequestHeaders.TryAddWithoutValidation("Authorization","Bearer " + authentication);
               var postReponse = await client.PostAsync("http://resz.azurewebsites.net/User/ValidateUser",formContent);
              postResponse.EnsureSuccessStatusCode();
    
               string resonse = await postResponse.Content.ReadAsStringAsync(); 
       }
    
    
      Yes,  the above code  from the client side you pass the parameter. And it gives me an idea on how to pass a parameter using clientPostAsync();
    
    
       Problem:
              Please show me or  let me know the example of  complete code on the WCF side on how to receive the parameters with it's complete attribute (Interface class and the class implementing the interface) .  Because I"m still having a problem on the WCF side.
    
  • EidandEidand GBMember, University ✭✭✭
    edited April 2015

    It's been a while since I used wcf but I think it's the same. If you check my controller on the api side you'll see that the input parameter for the call is a class with two properties matching exactly what you send in the formContent.

    So the wcf service would accept a class lets' call it UserDTO

    this class looks like this :

    using System.Runtime.Serialization;
    
    [DataContract]
    public sealed class UserDTO
    {
        [DataMember]
        public string Username {get;set;}
    
        [DataMember]
        public string Password {get;set;}
    }
    

    so that's your input parameter for your wcf call.

    Don't forget the DataContract on the class and DataMember for each property. I am pretty sure if you don't have those your input is going to be null. Any property not marked as [DataMember] will simply be ignored by the deserialiser.

    As I said, it's been a couple years since I touched wcf so I hope I remember correctly.

  • mcormcor USMember ✭✭

    Hi Andrei,

           Thanks for your reply (giving me an idea).  I just  do it  using JSON.  And it works.
    
  • Marcelo.8210Marcelo.8210 USMember

    Hi mcordovez!
    I have the same doubt of you. When I do Get call it is working, but I'm trying to do a Post call now.
    When I do post call from the client I'm getting the error end point wasnt found.

    I guess the problem is in WCF Code, I dont know if the UriTemplate is correct.

    Could you please help me?
    Thanks

    Here my WCF code:
    [OperationContract]
    [WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "SignIn/{email}/{password}")]
    MyUser SignIn(string email, string password);

    Client code:
    public async Task PostResponse() where T : class
    {

            var client = new System.Net.Http.HttpClient();
    
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    
        var postData = new List<KeyValuePair<string, string>>();
            postData.Add(new KeyValuePair<string, string>("email", email));
            postData.Add(new KeyValuePair<string, string>("password", password));
    
            var content = new System.Net.Http.FormUrlEncodedContent(postData);
    
            var response = await client.PostAsync("http://192.168.20.26/MyService/RestServiceImpl.svc/SignIn", content);
    
            var JsonResult = response.Content.ReadAsStringAsync().Result;
    
            if (typeof(T) == typeof(string))
                return null;
    
            var rootobject = JsonConvert.DeserializeObject<T>(JsonResult);
    
            return rootobject;
        }
    
  • EidandEidand GBMember, University ✭✭✭

    @Marcelo.8210, that's not how you build a post uri. you don't need to pass the email and password in the uri. that's very insecure.

    you uri is going to be SignIn and nothing else, you pass the data like in the example you quoted.

  • nattarSanthanarajnattarSanthanaraj USMember ✭✭

    I want to get the data coming from the HTTP response into string/ var for later use. for example, my response coming from the database is like this. [{"name":Raju","emp_id":"Tech_006"}]. I want to store the name and emp id in a separate string. how to store the data?
    this is my code:
    var client = new System.Net.Http.HttpClient();
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    var postData = new List<KeyValuePair<string, string>>();
    postData.Add(new KeyValuePair<string, string>("email", "[email protected]"));
    postData.Add(new KeyValuePair<string, string>("password", "techiva123"));
    var content = new System.Net.Http.FormUrlEncodedContent(postData);
    var response = await client.PostAsync("http://vps4.techiva.com/projects/Timesheet/public/api/login", content);
    var JsonResult = response.Content.ReadAsStringAsync().Result;
    DisplayAlert("value", JsonResult, "ok");-> // here it display the value [{"name":Raju","emp_id":"Tech_006"}] like this I want the name in a single string and emp id in a single string
    var rootobject = JsonConvert.DeserializeObject(JsonResult.ToString());

Sign In or Register to comment.