dongyuan8312 2015-04-03 08:58
浏览 182

如何使用httpwebrequest在c#中获取网页(使用ajax / javascript的php)的最终响应

I am using c# windows application. I have a php file that uses javascript/ajax to validate login and return some data. When I execute this in browser it works fine, but when I send data from c# windows application via httpwebrequest it does not return the complete response. c# does not get response of after submitting browser data.

Kindly help me on this.

Below is my code

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript"> 
function Ajaxcall(){    
$.ajax({        
url: "XXXXXXXX",    // this url is a moodle url and validate user authentication then returns roleid
type: "POST",
async:true,     
data: {username: uname, password: pwd, TransactionId: TransactionId},
error: function (data)
{
document.write("Error");            
},
success: function(response)
{                       
var url = 'login.php';
var form = $('<form action="' + url + '" method="post">' +
'<input type="text" name="RoleId" value="' + response + '" />'
'<input type="text" name="TransactionId" value="' + TransactionId + '" />'
'</form>');
$('body').append(form);
form.submit();
}
});
}
<?php 
//The below code will automatically execute after form submission
if (isset($_POST["RoleId"]))
{               
$NewRoleId =  $_POST["RoleId"];
$TransactionId = $_POST["TransactionId"];
$qry = "Update query is to update roleid in a table based on the transactionid";                
$result = mysql_query($qry);
if ($result)
echo "Updated successfully";
else
echo "Error in updating query";
exit();
}

'The below code runs when the page is loading and gets trnsactionid from the 'c#
if (isset($_POST['TransactionId']))
{               
    $qry = "select query returns username, password";
    echo "query:". $qry;
    $result = mysql_query($qry);

    if (mysql_num_rows($result) > 0)
    {
        $rows = mysql_fetch_array($result);                 
        echo "<script type='text/javascript'>var uname = '" . $rows["username"] . "', pwd = '" . $rows["password"] . "', TransactionId='" . $_POST['TransactionId'] . "';</script>";
       echo "<script language='JavaScript'>Ajaxcall(callbackfunction);  </script>";                 
    }
}
?>

C# code to post data:

String response = GetPost("XXXXX/Login.php", "TransactionId", "1")

public string GetPost(string Url, params string[] postdata)
{
    string result = string.Empty;
    string data = string.Empty;

    System.Text.ASCIIEncoding ascii = new ASCIIEncoding();

    if (postdata.Length % 2 != 0)
    {
        MessageBox.Show("Parameters must be even , \"user\" , \"value\" , ... etc", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
        return string.Empty;
    }

    for (int i = 0; i < postdata.Length; i += 2)
    {
         data += string.Format("&{0}={1}", postdata[i], postdata[i + 1]);
    }

    data = data.Remove(0, 1);

    byte[] bytesarr = ascii.GetBytes(data);

    try
    {
        WebRequest request = WebRequest.Create(Url);
        request.Method = "POST";
        request.ContentType = "application/x-www-form-urlencoded";
        request.ContentLength = bytesarr.Length;

        System.IO.Stream streamwriter = request.GetRequestStream();
        streamwriter.Write(bytesarr, 0, bytesarr.Length);
        streamwriter.Close();

        WebResponse response = request.GetResponse();
        streamwriter = response.GetResponseStream();

        System.IO.StreamReader streamread = new  System.IO.StreamReader(streamwriter);
        result = streamread.ReadToEnd();

        streamread.Close();
    }
    catch (Exception ex)
    {
         MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
    }

    return result;
}
  • 写回答

1条回答

  • dongshi1934 2015-04-03 09:51
    关注

    Try to add header() function to specify response manually

    评论

报告相同问题?

悬赏问题

  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大