Problem sending data from a console application to Webservice

Asked

Viewed 137 times

0

I have a console application that receives data from a mobile device, I am trying to send this data to a web service to process the data and fill them in the database.

I’m trying this way:

public static async Task PostWS(string dado)
{
    using (var httpClient = new HttpClient())
    {
        var url = @"rota do método no webservice";
        var jsonString = @"{'Packet': '" + dado+"'}";
        var content = new StringContent(jsonString, Encoding.UTF8, "application/json");
        content.Headers.Clear();
        content.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
        HttpResponseMessage resposta = httpClient.PostAsync(url, content).Result;
        if (resposta.IsSuccessStatusCode)
        {
            HttpContent conteudo = resposta.Content;
            string resultado = conteudo.ToString();
            Console.WriteLine("ok");
        }
        else
        {
            Console.WriteLine("erro");
        }
    }
    Console.ReadKey();
 }

I can access the method of my webservice the problem is that apparently I am not able to send the data correctly.

Webservice method I’m trying to access:

[HttpPost]
        [Route("teste")]
        public HttpResponseMessage testando(Device device)
        {
            string rout = ConfigurationManager.AppSettings["LogFile"];
            try
            {
                System.IO.File.AppendAllText(@rout, device.Packet);
                return Request.CreateResponse(HttpStatusCode.OK);
            }
            catch(Exception ex)
            {
                return Request.CreateResponse(HttpStatusCode.BadRequest, ex.Message);
            }
        }

I cannot write the data in the text file. NOTE: No errors.

Where am I going wrong ?

Thanks in advance.

  • "it does not access the method of my webservice" can explain it better? gives error, which error? is a post even? the Contenttype is correct?

2 answers

1


made without testing, may be necessary small adjustments, I believe that by Httpclient is the best, easiest way.

using System;

using System.Net.Http;

public class Program
{
    public static void Main()
    {
        using (var httpClient = new HttpClient())
        {
            var url = @"https://seusite.com";
            var jsonString = @"{'parametro': 'valor'}";
            var content = new StringContent(jsonString, Encoding.UTF8, "application/json");
            content.Headers.Clear();
            content.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
            HttpResponseMessage response = httpClient.PostAsync(url, content).Result;
            if (response.IsSuccessStatusCode)
            {
                HttpContent conteudo = resposta.Content;
                string resultado = await conteudo.ReadAsStringAsync();
                Console.WriteLine("ok");
            }
            else
            {
                Console.WriteLine("erro");
            }
        }

        Console.ReadKey();
    }
} 
}
  • 1

    Thank you for your reply. The method worked for me, but I had to comment on the lines "content.Headers.Clear();" and "content.Headers.Add("Content-Type", "application/x-www-form-urlencoded");", otherwise everything worked out. Thanks again :)

  • i put the x-www-form-urlencoded, pq saw in your question and then the default is to clear the header and then add the ones you want, in case it was the x-www-form-urlencoded

0

Hello, here’s an example for you:

[WebMethod]
public bool IsUserExist(string userName) {
    if (userName == "Teste")
     return true;
    else
     return false;
}

protected void Button2_Click(object sender, EventArgs e) {
    byte[] data = System.Text.Encoding.ASCII.GetBytes("userName=" + TextBox1.Text);

    System.Net.WebRequest request = System.Net.HttpWebRequest.Create("http://localhost/samples/MyService.asmx/IsUserExist");

    request.Method = "POST";
    request.ContentLength = data.Length;
    request.ContentType = "application/x-www-form-urlencoded";

    System.IO.Stream str = request.GetRequestStream();
    str.Write(data, 0, data.Length);
    str.Flush();
    System.Net.WebResponse response = request.GetResponse();
    System.IO.StreamReader reader = new System.IO.StreamReader(response.GetResponseStream());
    string result = reader.ReadToEnd();

    TextBox2.Text = result;
}

I hope it helps :)

  • Thank you for the answer, but I have some doubts. What is the usefulness of the two parameters of the Button2_click ? since you are not using them within the method. The other question is in the line "byte[] data = System.Text.Encoding.ASCII.Getbytes("username=" + Textbox1.Text);", what is the reason for "username=" ? thank you in advance.

  • the code provided by Dalton is windows form, need to adapt it

Browser other questions tagged

You are not signed in. Login or sign up in order to post.