views:

3090

answers:

3
+4  A: 

Hi Martin!

I was battling with the exact same problem a bit earlier (although in compact framework). Here's my question and my own answer to it: http://stackoverflow.com/questions/768641/asynchronous-webrequest-with-post-parameters-in-net-compact-framework

My version is asynchronous, so it's a bit more complex than what you're looking for, but the idea remains.

private string sendRequest(string url, string method, string postdata) {
    WebRequest rqst = HttpWebRequest.Create(url);

    // only needed, if you use HTTP AUTH
    //CredentialCache creds = new CredentialCache();
    //creds.Add(new Uri(url), "Basic", new NetworkCredential(this.Uname, this.Pwd));
    //rqst.Credentials = creds;
    rqst.Method = method;
    if (!String.IsNullOrEmpty(postdata)) {
        //rqst.ContentType = "application/xml";
        rqst.ContentType = "application/x-www-form-urlencoded";

        byte[] byteData = UTF8Encoding.UTF8.GetBytes(postdata);
        rqst.ContentLength = byteData.Length;
        using (Stream postStream = rqst.GetRequestStream()) {
            postStream.Write(byteData, 0, byteData.Length);
            postStream.Close();
        }
    }
    ((HttpWebRequest)rqst).KeepAlive = false;
    StreamReader rsps = new StreamReader(rqst.GetResponse().GetResponseStream());
    string strRsps = rsps.ReadToEnd();
    return strRsps;

}
Tommi Forsström
Hi Tommi, thanks for the sample. Unfortunately it doesn't seem to be working for me either. There are two typos in your code (you use 'req' when you create the StreamReader and i think its rqst?And then the streamIn i think is rsps (near the end).Despite that, I still get a 404 in that line: StreamReader rsps = new StreamReader(req.GetResponse().GetResponseStream());Question: If I don't want to use Credentials, can I skip that? I did it but it didn't work. This service doesn't req. user/pass
Martín Marconcini
Geez, sorry about the typos. I'll fix them in the answer right away.If it's 404 you're getting, then the problem is not in the code, you're just sending the wrong url. Put some breakpoints in the code sending the request and double-triple check that the url you're providing the Uri-constructor is valid.And yeah, of course you can skip the Credentials-part, I'll comment that out!
Tommi Forsström
Oh, and also, I need to change the content-type to "application/x-www-form-urlencoded" as you're sending regular POST params. In my case I was sending XML in the post params field and it mandated that content-type.
Tommi Forsström
Thanks Tommi, it was, as you also indicated, a problem with the URL (having an ending slash). :) Thanks for the code :)I will be surely using it.
Martín Marconcini
I recommend checking the asynchronous version found in the link provided in my answer. When sending (potentially sluggish) web requests, it's always a good thing to have the main thread nice and responsive while the data is being retrieved.
Tommi Forsström
Will do that, thanks!
Martín Marconcini
+2  A: 

Hi, see my answer to your other question. I believe your problem may not be your C# code. The web service URL accually returns a 404 with several other tools I used, but it returns the response you indicated if you leave off the trailing slash from the web service URL, so I suggest trying that.

Oddly, it doesn't seem to matter if the trailing URL is there when not doing SSL. Something strange with that web server, I guess.

Erv Walter
Erv, that was it! Thanks a lot. (And thanks to the other posters for the samples, I will surely use a mix of all these. You're my hero, as I've stated in the other question. :)
Martín Marconcini
Moral Of the story: Always tripple check what "other developers" tell you. (The web server programmer insisted that the URL had the slash, and I believed him). :S
Martín Marconcini
A: 

Hi,

dont know if u already resolved this issue, it´s a post from one year ago. I am Spanish and I am using mensario too.

to send and http request: (this is in ASP but the process is the same one)

Function enviarMsg2
   Dim oHTTP,inicio
   Dim strParametros
   Dim devolver

   Set oHTTP= server.CreateObject("Msxml2.ServerXMLHTTP")
   strParametros = "usuario="&usuario&"&clave="&clave&"&nserie="&nserie&"&     version=01010000&operacion=300&sms=1%0934635035526%0920041231233000%09Clinica+Paz%09Clinica+Paz+le+desea+Feliz+Navidad%2E&sms=2%0934612345678%0920041231233001%09Clinica+Paz%09Clinica+Paz+le+desea+Feliz+Navidad%2E"
'response.Write strParametros
'response.End
'Abrimos la conexión con el método POST, ya que estamos enviando una petición.
oHTTP.open "POST", "https://servicios.mensario.com/enviomasivo/apip", False

'Agregamos encabezados HTTP requeridos...
oHTTP.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"

'Enviamos la petición
oHTTP.send strParametros
devolver = oHTTP.responsetext

'Comprobamos si fue correcto         
inicio = Instr(devolver, "100 BIEN")
'response.Write "--->"&inicio
'response.End    
if inicio <=0 then
  enviarSMS2 = "Ha ocurrido un error en el envío del SMS."
else
  enviarSMS2 = Mid(devolver,inicio+9,len(devolver))
end if

Set oHTTP = Nothing

The only thing i dont have is a user /password for a try :)

Basicaly, when the response is "100 bien" the function returns that, otherwise it returns error.Hope it helps :)

jorge
Thanks for the response Jorge, we’ve already fixed the issue. The problem was that the mensario url had a “/“ at the end, which was incorrect.
Martín Marconcini