繁体   English   中英

如何用asp.net Web形式的args调用Restful服务?

[英]How to call restful service with args in asp.net web form?

我想在ASP.NET Web表单和C#中使用Restful服务。 所以我使用了HttpWebRequest,并且可以成功获得令牌。 但是我不能用参数调用Restful服务。 使用此代码,我尝试将BrokerId作为参数发送,但是我认为这是错误的,因为该服务显示了错误授权:

private void RemainInq(string Auth)
{
string Address = @"http://10.19.252.21:5003/Rest/Topup/RemainCreditInquiry";
Uri UriAddress = new Uri(Address);
var PostParam = "BrokerId=13000303";
var data = Encoding.ASCII.GetBytes(PostParam);
HttpWebRequest req = WebRequest.Create(UriAddress) as HttpWebRequest;
req.Method = "POST";
req.ContentType = "application/json";
req.Accept = "gzip,deflate";
req.ContentLength = data.Length;
req.Host = "10.19.252.21:5003";
req.Headers.Add("Authorization", Auth);
req.ContentLength = data.Length;
using (var strem = req.GetRequestStream())
{
strem.Write(data, 0, data.Length);
}
HttpWebResponse resp = req.GetResponse() as HttpWebResponse;
Encoding enc = System.Text.Encoding.GetEncoding(1252);
StreamReader loResponseStream = new StreamReader(resp.GetResponseStream(), enc);
string Response = loResponseStream.ReadToEnd();
string[] s = Response.Split(',');
for (int i = 0; i < s.Count(); ++i)
s[i] = s[i].Substring(s[i].IndexOf(":") + 2, s[i].LastIndexOf('"') - 
s[i].IndexOf(":") - 2);
loResponseStream.Close();
resp.Close();
}

终于我找到答案了。

private string[] CallSaleProvider(string YourParam1,string YourParam2)

    {

        var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://YourAddress");

        httpWebRequest.ContentType = "application/json";

        httpWebRequest.Method = "POST";

        httpWebRequest.Headers.Add("Authorization", Auth);

        using (var streamWriter = new

        StreamWriter(httpWebRequest.GetRequestStream()))

        {

            string json = new JavaScriptSerializer().Serialize(new

            {

                YourParam=Value, YourParam=value,YourParam=value


            });

            streamWriter.Write(json);

        }

        string result;

        var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();

        using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))

        {

            result = streamReader.ReadToEnd();

        }

        string[] s = result.Split(',');

        for (int i = 0; i < s.Count(); ++i)

            s[i] = s[i].Substring(s[i].IndexOf(":") + 2, s[i].LastIndexOf('"') - s[i].IndexOf(":") - 2);


        httpResponse.Close();

        return s;

    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM