原文:http://www.cnblogs.com/mvv118/p/5213660.html
此贴备用
public class JinShuJu
{
private static string Key = "9hh6fIbLOqDrgin4Q_r6X";
private static string Secret = "z3RSib8HeQBfau6zwRpRo";
/// <summary>
/// 获取表单API
/// </summary>
/// <returns></returns>
public static string GetFromAPI()
{
string uri = "https://jinshuju.net/api/v1/forms/RsE5EC";
string result = string.Empty;
WebRequest request = WebRequest.Create(new Uri(uri));
request.Credentials = GetCredentialCache(uri, Key, Secret);
request.Headers.Add("Authorization", GetAuthorization(Key, Secret));
request.Timeout = 2000;
WebResponse response = request.GetResponse();
Stream stream = response.GetResponseStream();
StreamReader sr = new StreamReader(stream);
result = sr.ReadToEnd();
sr.Close();
stream.Close();
return result;
}
/// <summary>
/// 提交数据API
/// </summary>
/// <param name="JSONData"></param>
/// <returns></returns>
public static string PostFromAPI(string JSONData)
{
string uri = "https://jinshuju.net/api/v1/forms/RsE5EC";
string result = string.Empty;
WebRequest request = WebRequest.Create(new Uri(uri));
request.Credentials = GetCredentialCache(uri, Key, Secret);
request.Headers.Add("Authorization", GetAuthorization(Key, Secret));
request.Timeout = 2000;
byte[] bytes = Encoding.UTF8.GetBytes(JSONData);
request.Method = "POST";
request.ContentType = "application/json";
string paraUrlCoded = JSONData;
byte[] payload;
payload = System.Text.Encoding.UTF8.GetBytes(paraUrlCoded);
request.ContentLength = payload.Length;
Stream writer = request.GetRequestStream();
writer.Write(payload, 0, payload.Length);
writer.Close();
WebResponse response = request.GetResponse();
Stream stream = response.GetResponseStream();
StreamReader sr = new StreamReader(stream);
result = sr.ReadToEnd();
sr.Close();
stream.Close();
return result;
}
#region # 生成 Http Basic 访问凭证 #
private static CredentialCache GetCredentialCache(string uri, string username, string password)
{
string authorization = string.Format("{0}:{1}", username, password);
CredentialCache credCache = new CredentialCache();
credCache.Add(new Uri(uri), "Basic", new NetworkCredential(username, password));
return credCache;
}
private static string GetAuthorization(string username, string password)
{
string authorization = string.Format("{0}:{1}", username, password);
return "Basic " + Convert.ToBase64String(new ASCIIEncoding().GetBytes(authorization));
}
#endregion
}