.net 使用http摘要认证,返回json数据
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net; namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
String outMsg=""; String result= Request("url",
"GET", "", "", out outMsg); Console.WriteLine(result); Console.WriteLine(outMsg); Console.ReadKey();
} public static string Request(string sUrl, string sMethod, string sEntity, string sContentType,
out string sMessage)
{
try
{
sMessage = "";
using (System.Net.WebClient client = new System.Net.WebClient())
{
client.Credentials = CreateAuthenticateValue(sUrl); WebHeaderCollection customerHeader= new WebHeaderCollection();
customerHeader.Add(HttpRequestHeader.Accept, "application/json");
customerHeader.Add(HttpRequestHeader.ContentType, "application/json;charset=UTF-8"); client.Headers = customerHeader; Uri url = new Uri(sUrl);
byte[] bytes = Encoding.UTF8.GetBytes(sEntity);
byte[] buffer;
switch (sMethod.ToUpper())
{
case "GET":
buffer = client.DownloadData(url);
break;
case "POST":
buffer = client.UploadData(url, "POST", bytes);
break;
default:
buffer = client.UploadData(url, "POST", bytes);
break;
} return Encoding.UTF8.GetString(buffer);
}
}
catch (WebException ex)
{
sMessage = ex.Message;
var rsp = ex.Response as HttpWebResponse;
var httpStatusCode = rsp.StatusCode;
var authenticate = rsp.Headers.Get("WWW-Authenticate"); return "";
}
catch (Exception ex)
{
sMessage = ex.Message;
return "";
}
} private static CredentialCache CreateAuthenticateValue(string sUrl)
{
CredentialCache credentialCache = new CredentialCache();
credentialCache.Add(new Uri(sUrl), "Digest", new NetworkCredential("admin", "password")); return credentialCache;
}
}
}