我想在asp.net webform和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();
}
答案 0 :(得分:1)
最后我能找到答案。
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;
}