http+json
public string PostHttp(string url, string body,string token)
{
try
{
HttpWebRequest Request = (HttpWebRequest)WebRequest.Create(url);
Request.ContentType = "application/json;charset=utf8";
Request.Headers.Add("Authorization", token);
Request.Timeout = 30 * 1000;
Request.Method = "POST";
byte[] btBodys = Encoding.GetEncoding("utf-8").GetBytes(body);
Request.ContentLength = btBodys.Length;
Request.GetRequestStream().Write(btBodys, 0, btBodys.Length);
using (HttpWebResponse httpWebResponse = (HttpWebResponse)Request.GetResponse())
{
StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream());
string responseContent = streamReader.ReadToEnd();
httpWebResponse.Close();
streamReader.Close();
Request.Abort();
return responseContent;
}
}
catch (Exception ex)
{
//这里记录日志
return "error" + ex.Message;
}
}
http form-data
public string HttpPost_formdata(string url,string token)
{
//获取id和key
//string ID = Appsettings.app("JinHePushData", "ID").ToString();//ID
//string KEY = Appsettings.app("JinHePushData", "KEY").ToString();//KEY
//string EncryptedString = ID + ":" + KEY;
//string base64 = "Basic " + EncodeBase64(EncryptedString);
string result = "";
try
{
var request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.AllowAutoRedirect = true;
request.Timeout = 20 * 1000;
request.ContentType = "application/x-www-form-urlencoded";
StringBuilder buffer = new StringBuilder();
buffer.AppendFormat("{0}={1}&", "grant_type", "client_credentials");
buffer.AppendFormat("{0}={1}", "scope", "write");
var byteArray = Encoding.Default.GetBytes(buffer.ToString());
request.ContentLength = byteArray.Length;
using (var newStream = request.GetRequestStream())
{
newStream.Write(byteArray, 0, byteArray.Length);
newStream.Close();
}
request.Headers.Add("Authorization", token);
var response = (HttpWebResponse)request.GetResponse();
var rspStream = response.GetResponseStream();
using (var reader = new StreamReader(rspStream, Encoding.UTF8))
{
result = reader.ReadToEnd();
rspStream.Close();
}
response.Close();
}
catch (Exception ex)
{
result = ex.Message.ToString();
}
return result;
}