首页 > 代码库 > C# http get与post请求方法
C# http get与post请求方法
using System;using System.Data;using System.Configuration;using System.Linq;using System.Web;using System.Web.Security;using System.Web.UI;using System.Web.UI.HtmlControls;using System.Web.UI.WebControls;using System.Web.UI.WebControls.WebParts;using System.Xml.Linq;using System.Net;using System.IO;using System.Text;using System.Collections.Generic;namespace WebAppTest{ public class HttpTools { public static string GetRequest(string url) { HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url); request.Method = "get"; HttpWebResponse response = (HttpWebResponse)request.GetResponse(); using(StreamReader sr = new StreamReader(response.GetResponseStream(),Encoding.UTF8)) { string result = sr.ReadToEnd(); return result; } } public static string PostRequest(string url,Dictionary<object,object> paramList) { HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url); StringBuilder sb = new StringBuilder(); foreach (var item in paramList) { sb.Append(item.Key + "=" + item.Value + "&"); } //将参数拼为:"name=test&pwd=123" 这种字符串格式 然后将字符串转为byte数组 最后将byte数组写入请求流中 string paramData = http://www.mamicode.com/sb.ToString().Trim(‘&‘); byte[] data =http://www.mamicode.com/ System.Text.Encoding.UTF8.GetBytes(paramData); //设置post方式 request.Method = "post"; //这句不能少 不难post请求 得不到对应的响应结果 request.ContentType = "application/x-www-form-urlencoded"; //设置请求参数的长度 request.ContentLength = data.Length; Stream stream = request.GetRequestStream(); stream.Write(data, 0, data.Length); stream.Close(); /** * *****************注意事项******************** * * 不管是get还是post请求最后得到的响应流不能直接stream * 不难得不到响应结果 * * * 直接使用Stream 不能获取响应的结果值 * * 要使用StreamReader才能获取响应的结果值 * * Stream stream = response.GetResponseStream(); * * byte[] data = http://www.mamicode.com/new byte[2*1024*1024]>*/ HttpWebResponse response = (HttpWebResponse)request.GetResponse(); using(StreamReader sr = new StreamReader(response.GetResponseStream(),Encoding.UTF8)) { string result = sr.ReadToEnd(); return result; } } }}
C# http get与post请求方法
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。