此处内容传输都是用UTF-8编码
1.不带参数发送Post请求
/// <summary>
/// 指定Post地址使用Get 方式获取全部字符串
/// </summary>
/// <param name="url">请求后台地址</param>
/// <returns></returns>
public static string Post(string url)
{
string result = "";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.Method = "POST";
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
Stream stream = resp.GetResponseStream();
//获取内容
using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
{
result = reader.ReadToEnd();
}
return result;
}
2.带参数Post请求,指定键值对
/// <summary>
/// 指定Post地址使用Get 方式获取全部字符串
/// </summary>
/// <param name="url">请求后台地址</param>
/// <returns></returns>
public static string Post(string url,Dictionary<string,string> dic)
{
string result = "";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
#region 添加Post 参数
StringBuilder builder = new StringBuilder();
int i = 0;
foreach (var item in dic)
{
if (i > 0)
builder.Append("&");
builder.AppendFormat("{0}={1}", item.Key, item.Value);
i++;
}
byte[] data = Encoding.UTF8.GetBytes(builder.ToString());
req.ContentLength = data.Length;
using (Stream reqStream = req.GetRequestStream())
{
reqStream.Write(data, 0, data.Length);
reqStream.Close();
}
#endregion
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
Stream stream = resp.GetResponseStream();
//获取响应内容
using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
{
result = reader.ReadToEnd();
}
return result;
}
3.带参数的Post请求,指定发送字符串内容
/// <summary>
/// 指定Post地址使用Get 方式获取全部字符串
/// </summary>
/// <param name="url">请求后台地址</param>
/// <param name="content">Post提交数据内容(utf-8编码的)</param>
/// <returns></returns>
public static string Post(string url, string content)
{
string result = "";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
#region 添加Post 参数
byte[] data = Encoding.UTF8.GetBytes(content);
req.ContentLength = data.Length;
using (Stream reqStream = req.GetRequestStream())
{
reqStream.Write(data, 0, data.Length);
reqStream.Close();
}
#endregion
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
Stream stream = resp.GetResponseStream();
//获取响应内容
using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
{
result = reader.ReadToEnd();
}
return result;
}
转载方法:
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create("http://fanyi.baidu.com/transcontent");
Encoding encoding = Encoding.UTF8;
string param = "ie=utf-8&source=txt&query=hello&t=1327829764203&token=8a7dcbacb3ed72cad9f3fb079809a127&from=auto&to=auto";
//encoding.GetBytes(postData);
byte[] bs = Encoding.ASCII.GetBytes(param);
string responseData = String.Empty;
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = bs.Length;
using (Stream reqStream = req.GetRequestStream())
{
reqStream.Write(bs, 0, bs.Length);
reqStream.Close();
}
using (HttpWebResponse response = (HttpWebResponse)req.GetResponse())
{
using (StreamReader reader = new StreamReader(response.GetResponseStream(),encoding))
{
responseData = reader.ReadToEnd().ToString();
}
context.Response.Write(responseData);
}
4.发送get请求
public static string Get(string Url)
{
//System.GC.Collect();
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
request.Proxy = null;
request.KeepAlive = false;
request.Method = "GET";
request.ContentType = "application/json; charset=UTF-8";
request.AutomaticDecompression = DecompressionMethods.GZip;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream myResponseStream = response.GetResponseStream();
StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.UTF8);
string retString = myStreamReader.ReadToEnd();
myStreamReader.Close();
myResponseStream.Close();
if (response != null)
{
response.Close();
}
if (request != null)
{
request.Abort();
}
return retString;
}
5.发送json内容和header设置
private void postjson()
{
string RobotID = Web.DLL.Utility.RequestUtility.GetString("RobotID");//header
string phoneNumber = Web.DLL.Utility.RequestUtility.GetString("phoneNumber");
int remainingTime_min = Web.DLL.Utility.RequestUtility.GetInt("remainingTime_min", 0);
string url = "https://lsrobottest.lscure.com:1800/Robot/WebDeviceInfo";
//Hashtable hash_json = new Hashtable();
//hash_json.Add("phoneNumber", phoneNumber);
//hash_json.Add("remainingTime_min", remainingTime_min);
string hash_json = "{\"phoneNumber\": \"" + phoneNumber + "\",\"remainingTime_min\": " + remainingTime_min + "}";
Hashtable hash_header = new Hashtable();
hash_header.Add("RobotID", RobotID);
Response.Write(PostJson(url, hash_json.ToString(), hash_header));
Response.End();
}
private string PostJson(string url, string postData, Hashtable headht = null)
{
//https的需要加着两行----------------
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
ServicePointManager.SecurityProtocol = (SecurityProtocolType)192 | (SecurityProtocolType)768 | (SecurityProtocolType)3072;
//------------------
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "application/json;charset=UTF-8";
request.Accept = "application/json";
#region headers设置
if (headht != null)
{
foreach (DictionaryEntry item in headht)
{
request.Headers.Add(item.Key.ToString(), item.Value.ToString());
}
}
#endregion
byte[] paramJsonBytes;
paramJsonBytes = System.Text.Encoding.UTF8.GetBytes(postData);
request.ContentLength = paramJsonBytes.Length;
Stream writer;
try
{
writer = request.GetRequestStream();
}
catch (Exception e)
{
writer = null;
Response.Write("连接服务器失败:" + e.ToString());
Response.End();
}
writer.Write(paramJsonBytes, 0, paramJsonBytes.Length);
writer.Close();
HttpWebResponse response;
try
{
response = (HttpWebResponse)request.GetResponse();
}
catch (WebException ex)
{
response = ex.Response as HttpWebResponse;
}
Stream resStream = response.GetResponseStream();
StreamReader reader = new StreamReader(resStream);
string text = reader.ReadToEnd();
return text;
}
6.腾讯文档里的用例:
private const string sContentType = "application/x-www-form-urlencoded";
private const string sUserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.2; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";
public static string Send(string data, string url)
{
return Send(Encoding.GetEncoding("UTF-8").GetBytes(data), url);
}
public static string Send(byte[] data, string url)
{
Stream responseStream;
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
if (request == null)
{
throw new ApplicationException(string.Format("Invalid url string: {0}", url));
}
// request.UserAgent = sUserAgent;
request.ContentType = sContentType;
request.Method = "POST";
request.ContentLength = data.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(data, 0, data.Length);
requestStream.Close();
try
{
responseStream = request.GetResponse().GetResponseStream();
}
catch (Exception exception)
{
throw exception;
}
string str = string.Empty;
using (StreamReader reader = new StreamReader(responseStream, Encoding.GetEncoding("UTF-8")))
{
str = reader.ReadToEnd();
}
responseStream.Close();
return str;
}
方法调用:
Hashtable hash = new Hashtable();
Web.DLL.wxItem.userlist u = islogin();
if (u != null)
{
string page_url = Web.DLL.Utility.RequestUtility.GetString("page_url");
WX_About wa = new WX_About();
string access_token = wa.getaccess_token(1);
string url = "https://api.weixin.qq.com/wxa/genwxashortlink?access_token=" + access_token;
string returnStr = HttpUtil.Send("{\"page_url\": \"" + page_url + "\"}", url);
errorclass errmode = JsonConvert.DeserializeObject<errorclass>(returnStr);
if (errmode.ErrCode == 0)
{
hash["error"] = 0;
hash["errorstr"] = "获取成功";
hash["data"] = returnStr;
}
else
{
hash["error"] = 1;
hash["data"] = returnStr;
hash["errorstr"] = "获取失败";
}
}
else
{
hash["error"] = -1;
hash["errorstr"] = "请先登录";
}
Response.Write(JsonMapper.ToJson(hash));
Response.End();