Created
May 7, 2011 03:38
-
-
Save azyobuzin/960178 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Net; | |
using System.Security.Cryptography; | |
using System.Text; | |
using System.Xml.Linq; | |
namespace Azyobuzi.HatenaDiaryClient.Models.Hatena | |
{ | |
public static class WsseAtomConnection | |
{ | |
private static Random random = new Random(); | |
private static string CreateHeader(string userName, string password) | |
{ | |
var tmp = new byte[25]; | |
random.NextBytes(tmp); | |
var nonce = Convert.ToBase64String(tmp); | |
tmp = null; | |
var created = DateTime.Now.ToUniversalTime().ToString("o"); | |
var digest = Convert.ToBase64String( | |
new SHA1Managed().ComputeHash( | |
Encoding.ASCII.GetBytes(nonce + created + password) | |
)); | |
return string.Format( | |
@"X-WSSE:UsernameToken Username=""{0}"", PasswordDigest=""{1}"", Nonce=""{2}"", Created=""{3}""", | |
userName, digest, nonce, created); | |
} | |
public static XDocument Get(string reqUri, string userName, string password) | |
{ | |
using (var wc = new WebClient()) | |
{ | |
wc.Headers.Add(CreateHeader(userName, password)); | |
using (var stream = wc.OpenRead(reqUri)) | |
return XDocument.Load(stream); | |
} | |
} | |
public static void Delete(string reqUri, string userName, string password) | |
{ | |
var req = WebRequest.Create(reqUri); | |
req.Method = "DELETE"; | |
req.Headers.Add(CreateHeader(userName, password)); | |
req.GetResponse().Close(); | |
} | |
private static XDocument PostOrPut(string reqUri, string method, XDocument reqData, string userName, string password) | |
{ | |
var req = WebRequest.Create(reqUri); | |
req.Method = method; | |
req.Headers.Add(CreateHeader(userName, password)); | |
req.ContentType = "application/x.atom+xml"; | |
var bs = Encoding.UTF8.GetBytes(reqData.ToString()); | |
req.ContentLength = bs.Length; | |
using (var stream = req.GetRequestStream()) | |
stream.Write(bs, 0, bs.Length); | |
using (var res = req.GetResponse()) | |
return XDocument.Load(res.GetResponseStream()); | |
} | |
public static XDocument Post(string reqUri, XDocument reqData, string userName, string password) | |
{ | |
return PostOrPut(reqUri, "POST", reqData, userName, password); | |
} | |
public static XDocument Put(string reqUri, XDocument reqData, string userName, string password) | |
{ | |
return PostOrPut(reqUri, "PUT", reqData, userName, password); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment