POST REQUEST DOENS'T WORK

RaffynaRaffyna ITMember

Hi, I'm a new in this forum and I need you!
I implemented a method that do http POST request.
When I call the method my class don't send parameters to backend:
Can you help me?
This is my method :

private async Task<Survey> GetToken(string serviceUri)
       {
           try
           {

               string postParameters = string.Format(Constants.TagSubject + "={0}&" + Constants.TagType + "={1}&" + Constants.TagCategory + "={2}&" +   Constants.TagInterval + "={3}", Constants.SubjectFeedback, Constants.TypeSelect, Constants.CategoryCubotti, Constants.IntervalWeek);
               HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(serviceUri);
               request.Method = "POST";
               request.ContentType = "application/json";

               byte[] dataStream = Encoding.Unicode.GetBytes(postParameters);
               Stream newStream = await request.GetRequestStreamAsync();
               newStream.Write(dataStream, 0, dataStream.Length);
               newStream.Flush();
               newStream.Dispose();

               var response = (HttpWebResponse)await request.GetResponseAsync();
               if (response.StatusCode == HttpStatusCode.OK)
               {
                   using (Stream responseStream = response.GetResponseStream())
                   {
                       using (StreamReader reader = new StreamReader(responseStream))
                       {

                           string str = reader.ReadToEnd();
                           var survey = JsonConvert.DeserializeObject<Survey>(str);
                           survey.SurveyToString();
                           System.Diagnostics.Debug.WriteLine("SERVER RESPONSE JSON: " + survey.SurveyToString());
                           return survey;
                       }
                   }
               }
           }
           catch (Exception e)
           {
               System.Diagnostics.Debug.WriteLine("SERVER RESPONSE ERROR: " + e.Message);
           }
           return null;

       }

Thanks in advance

Posts

  • ClowningClowning USMember ✭✭

    Hey @Raffyna ,

    are you sure that your code does not return null?

    By the way, I advice you to use the HttpClient library... It's more simple !

    An exemple :

        public static async Task<APILogin> login(string _email, string _password)
        {
    
    
            using (HttpClient client = new HttpClient())
            {
    
                    APILogin dataResponse = await Task.Factory.StartNew(() =>
                   {
    
                       try
                       {
                           APILogin stuff;
                           string postdataJson = JsonConvert.SerializeObject(new { email = _email, password = _password });
                           var postdataString = new StringContent(postdataJson, new UTF8Encoding(), "application/json");
    
                           var responseObj = client.PostAsync("YOURENDPOINT", postdataString);
    
                           responseString = responseObj.Result.Content.ReadAsStringAsync().Result;
    
                           if (responseObj.Result.IsSuccessStatusCode)
                           {
                               stuff = JsonConvert.DeserializeObject<APILogin>(responseString);
                               stuff.error = false;
                           }
                           else {
                               stuff = new APILogin(true);
                           }
    
                           return stuff;
                       }
                       catch {
    
                           var stuff = new APILogin(true);
                           return stuff;
                    }
    
                });
    
                return dataResponse;
            }
    
        }
    

    Maybe my way is the better but if think it's better than your method and more simple.

    Writeline return what ?

  • NMackayNMackay GBInsider, University mod

    @Raffyna

    As Jonathan suggests, use HTTPClient instead, especially if your using PCL.

  • RaffynaRaffyna ITMember

    Hi @Clowning ,
    thanks for the reply.
    I used HTTPClient but the "responseString" return "Parameters Null".
    The backend system return "Parameters Null" when "Count($_POST)" is equal to zero.

    public async Task PostRequest(string url)
    {
    using (HttpClient client = new HttpClient())
    {
    string dataResponse = await Task.Factory.StartNew(() =>
    {
    string stuff;
    string postdataJson = "subject=" + JsonConvert.SerializeObject(new { subject = "mood", type = "insert", mood = 1, category = 1, feedback = "test-10-6-2016" });
    var postdataString = new StringContent(postdataJson, new UTF8Encoding(), "application/json");

                    var responseObj = client.PostAsync(url, postdataString);
    
                    var responseString = responseObj.Result.Content.ReadAsStringAsync().Result;
    
                    if (responseObj.Result.IsSuccessStatusCode)
                    {
                        stuff = JsonConvert.DeserializeObject<string>(responseString);
                    }
                    else
                    {
                        stuff = "error";
                    }
                    return stuff;
                });
    
                return dataResponse;
            }
       }
    
  • AdamPAdamP AUUniversity ✭✭✭✭✭
    edited June 2016

    @Raffyna - make sure you await all async functions. e.g.

    var responseObj = await client.PostAsync(url, postdataString);
    
    var responseString = await responseObj.Result.Content.ReadAsStringAsync();
    

    Also I suggest removing the Task.Factory.StartNew it isn't needed

  • ClowningClowning USMember ✭✭

    for " Task.Factory.StartNew " you're right, it isn't needed but when i remove it i my gui is block ! it's weird !

  • AdamMeaneyAdamMeaney USMember ✭✭✭✭✭

    That's because of the .Result calls. await anything that you were using .Result on, and after the first one use .ConfigureAwait(false).

  • RaffynaRaffyna ITMember
    edited June 2016

    Hi Guys,
    I found a solution.

    using (HttpClient client = new HttpClient()){
    string stuff;
    var postdataJson = JsonConvert.SerializeObject(new { subject = "feedback", type = "select", category = 1, interval = "week" });
    var values = new Dictionary<string, string>();
    values.Add("json", postdataJson);
    var content = new FormUrlEncodedContent(values);
    var responseObj = await client.PostAsync(url, content);
    var responseString = await responseObj.Content.ReadAsStringAsync();
    if (responseObj.IsSuccessStatusCode)
    {
    stuff = JsonConvert.DeserializeObject(responseString);
    }
    else
    {
    stuff = "error";
    }
    return responseString;

    Thanks!

Sign In or Register to comment.