簡體   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