yejiKim
yejiKim

Reputation: 31

c# HttpWebRequest get response string

I'm trying to send some data through HTTPS Post without certification. But I'm getting null however that response status code is OK. Why is this? Any help would be greatly appreciated.

I want to receive "hello" string from https://test.com/post_test.php. I saw many examples related to this, but none is working for me. Does anyone know what I am missing? Can some one guide me how to do that?

Thanks in advance!

c# code:

    private static bool ValidateRemoteCertificate(object sender,X509Certificate certificate,X509Chain chain,SslPolicyErrors policyErrors)
    {
        return true;
    }

    private String SendHttpWebPost(string strUrl, string strData)
    {
        string result = string.Empty;
        ServicePointManager.ServerCertificateValidationCallback += new System.Net.Security.RemoteCertificateValidationCallback(ValidateRemoteCertificate);

        HttpWebRequest request = null;
        HttpWebResponse response = null;
        try
        {
            Uri url = new Uri(strUrl);
            request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = WebRequestMethods.Http.Post;
            request.KeepAlive = true;
            request.Timeout = 5000;

            // encoding
            byte[] data = Encoding.UTF8.GetBytes(strData);
            request.ContentType = "application/json";
            request.ContentLength = data.Length;

            // send request
            Stream dataStream = request.GetRequestStream();
            dataStream.Write(data, 0, data.Length);
            dataStream.Flush();
            dataStream.Close();

            // get response
            response = (HttpWebResponse)request.GetResponse();
            Stream responseStream = response.GetResponseStream();
            string strStatus = ((HttpWebResponse)response).StatusDescription;
            StreamReader streamReader = new StreamReader(responseStream);
            result = streamReader.ReadToEnd();

            // close connection
            streamReader.Close();
            responseStream.Close();
            response.Close();
        }
        catch (Exception ex)
        {
            return ex.Message;
        }
        return result;
    }

    private void Form1_Load(object sender, EventArgs e)
    {
            MessageBox.Show(SendHttpWebPost("https://test.com/post_test.php", "data=hello"));
    }

php code:

    <?php
            echo($_REQUEST["data"]);
    ?>

Upvotes: 1

Views: 10235

Answers (1)

PepitoSh
PepitoSh

Reputation: 1836

Why don't you just simply request the Url without any fancy?

HttpWebRequest Request = (HttpWebRequest)WebRequest.Create(strUrl);
Request.Method = "GET";
Request.KeepAlive = true;

HttpWebResponse Response = (HttpWebResponse)Request.GetResponse();

if (Response.StatusCode == HttpStatusCode.OK) {
     ....
}

Upvotes: 3

Related Questions