您的位置:首页 > 理论基础 > 计算机网络

C#、asp.net访问基于http basic验证的api原理

2007-08-25 19:32 766 查看
注意引入命名空间
using System.Net;
using System.Text;
using System.IO;
具体核心代码:
WebRequest wr = WebRequest.Create(rssurl);//其中rssurl为要调用的api地址
wr.Method = "POST";指定调用方式get post
wr.ContentType = "application/x-www-form-urlencoded";
NetworkCredential nc = new NetworkCredential("username", "password", "");
wr.Credentials = nc;//传入httpbasic验证的用户名、密码
string data="";//传入需要给api的参数
StringBuilder UrlEncoded = new StringBuilder();
byte[] SomeBytes = null;
if (data != null)
{
ASCIIEncoding encodedData=new ASCIIEncoding();
SomeBytes=encodedData.GetBytes(data);
wr.ContentLength = SomeBytes.Length;
Stream newStream = wr.GetRequestStream();
newStream.Write(SomeBytes, 0, SomeBytes.Length);
newStream.Close();
}
else
{
wr.ContentLength = 0;
}
string re = "";
try
{
WebResponse result = wr.GetResponse();
Stream ReceiveStream = result.GetResponseStream();

Byte[] read = new Byte[512];
int bytes = ReceiveStream.Read(read, 0, 512);

re = "";
while (bytes > 0)
{
// 注意:
// 下面假定响应使用 UTF-8 作为编码方式。
// 如果内容以 ANSI 代码页形式(例如,932)发送,则使用类似下面的语句:
// Encoding encode = System.Text.Encoding.GetEncoding("shift-jis");
Encoding encode = System.Text.Encoding.GetEncoding("gb2312");
re += encode.GetString(read, 0, bytes);
bytes = ReceiveStream.Read(read, 0, 512);
}
}
catch (Exception e)
{
re = e.Message;
}
return re;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: