Http GET、Post方式的请求总结

读取http响应信息,并返回响应体

        /// <summary>
        /// 读取http响应信息,并返回响应体
        /// </summary>
        /// <param name="response">HttpWebResponse对象</param>
        /// <returns></returns>
        public static string ReaderFromHttp(HttpWebResponse response)
        {
            Stream stream = null;
            StreamReader streamReader = null;
            try
            {
                var contentEncoding = response.ContentEncoding; //压缩标志
                var characterSet = response.CharacterSet;       //字符集

                stream = response.GetResponseStream();
                if (contentEncoding == "gzip")
                {
                    /*压缩数据,要进行处理*/
                    throw new NotImplementedException("gzip压缩数据处理还么实现");
                }
                else
                {
                    streamReader = new StreamReader(stream, Encoding.GetEncoding(characterSet));
                    return streamReader.ReadToEnd();
                }

            }
            catch (Exception e)
            {
                return null;
            }
            finally
            {
                if (streamReader != null)
                {
                    streamReader.Close();
                    streamReader = null;
                }
                if (stream != null)
                {
                    stream.Close();
                    stream = null;
                }
            }
        }

Http  Get

        #region  Get Http

        /// <summary>
        /// GET方式的HTTP请求
        /// </summary>
        /// <param name="targetUri"></param>
        /// <param name="timeout">超时时间</param>
        /// <param name="cookie">随同HTTP请求发送的Cookie信息</param>
        /// <returns></returns>
        public static HttpWebRequest CreateGetHttpWebRequest(string targetUri, int timeout = 0, CookieCollection cookie = null)
        {
            HttpWebRequest request = WebRequest.Create(targetUri) as HttpWebRequest;
            request.UserAgent = DefaultUserAgent;
            request.Method = "GET";

            if (timeout != 0)
                request.Timeout = timeout;
            if (cookie != null)
            {
                request.CookieContainer = new CookieContainer();
                request.CookieContainer.Add(cookie);
            }

            return request;
        }

        /// <summary>
        /// GET方式的HTTP请求,返回响应体
        /// </summary>
        /// <param name="targetUri"></param>
        /// <param name="timeout">超时时间</param>
        /// <param name="cookie">随同HTTP请求发送的Cookie信息</param>
        /// <returns></returns>
        public static string ReturnFromGetHttp(string targetUri, int timeout = 0, CookieCollection cookie = null)
        {
            HttpWebRequest request = null;
            HttpWebResponse response = null;
            try
            {
                request = CreateGetHttpWebRequest(targetUri, timeout, cookie);
                response = request.GetResponse() as HttpWebResponse;

                return ReaderFromHttp(response);
            }
            catch (Exception e)
            {
                return null;
            }
            finally
            {
                if (response != null)
                {
                    response.Close();
                    response = null;
                }
                if (request != null)
                {
                    request.Abort();
                    request = null;
                }
            }
        }

        #endregion

Http Post

        #region  Post Http

        /// <summary>
        /// POST方式的HTTP请求
        /// </summary>
        /// <param name="targetUri"></param>
        /// <param name="content">请求文本信息</param>
        /// <param name="characterSet">字符集(默认utf-8)</param>
        /// <param name="timeout">超时时间</param>
        /// <param name="cookie">随同HTTP请求发送的Cookie信息</param>
        /// <returns></returns>
        public static HttpWebRequest CreatePostHttpWebRequest(string targetUri, string content, string characterSet = null, int timeout = 0, CookieCollection cookie = null)
        {
            HttpWebRequest request = WebRequest.Create(targetUri) as HttpWebRequest;
            request.UserAgent = DefaultUserAgent;
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.Headers.Add("Accept-Encoding", "gzip, deflate");

            if (timeout != 0)
                request.Timeout = timeout;
            if (cookie != null)
            {
                request.CookieContainer = new CookieContainer();
                request.CookieContainer.Add(cookie);
            }

            using (var stream = request.GetRequestStream())  //写入请求数据流
            {
                characterSet = string.IsNullOrEmpty(characterSet) ? "utf-8" : characterSet;
                var bytes = Encoding.GetEncoding(characterSet).GetBytes(content);
                request.ContentLength = bytes.LongLength;
                stream.Write(bytes, 0, bytes.Length);
            }

            return request;
        }

        /// <summary>
        /// POST方式的HTTP请求,返回响应体
        /// </summary>
        /// <param name="targetUri"></param>
        /// <param name="content">请求文本信息</param>
        /// <param name="characterSet">字符集(默认utf-8)</param>
        /// <param name="timeout">超时时间</param>
        /// <param name="cookie">随同HTTP请求发送的Cookie信息</param>
        /// <returns></returns>
        public static string ReturnFromPostHttp(string targetUri, string content, string characterSet = null, int timeout = 0, CookieCollection cookie = null)
        {
            HttpWebRequest request = null;
            HttpWebResponse response = null;
            try
            {
                request = CreatePostHttpWebRequest(targetUri,content,characterSet, timeout, cookie);
                response = request.GetResponse() as HttpWebResponse;

                return ReaderFromHttp(response);
            }
            catch (Exception e)
            {
                return null;
            }
            finally
            {
                if (response != null)
                {
                    response.Close();
                    response = null;
                }
                if (request != null)
                {
                    request.Abort();
                    request = null;
                }
            }
        }

        #endregion

调用方式:

var reval = ReturnFromGetHttp("http://www.douyou100.com");
var reval1 = ReturnFromPostHttp("http://www.douyou100.com","请求文本");

时间: 2024-10-11 13:15:52

Http GET、Post方式的请求总结的相关文章

C# Post Get 方式发送请求

httpPost 方式发送请求 不带参数 1 /// <summary> 2 /// 没有参数的post请求 3 /// </summary> 4 public void HttpPostNoParam() 5 { 6 string Url = "请求地址"; 7 HttpWebRequest request = WebRequest.CreateHttp(Url); 8 request.Method = "POST"; 9 request.

struts2 跳转方式,请求分派,重定向

http://localhost:8080/s2_05_HCM_05/hcm/employee/helloworld1.action 成员中的信息默认会保存在request 范围中.注意属性应该保证有set方法.2.默认的转发方式是请求分派 3.http://localhost:8080/s2_05_HCM_05/hcm/employee/message<!-- 如果没有找到指定result,会到继承的base package中找 --> 4.测试重定向 重定向的时候,不能定向到WEB-INF

c# post方式发送请求

public static bool CheckNew(string serverIP) { bool passed = false; try { string url = string.Format("http://{0}/login/index", serverIP); //encoding Encoding gb2312 = Encoding.GetEncoding("GB2312"); //创建连接 HttpWebRequest mHttpRequest =

python实现的json数据以HTTP GET,POST,PUT,DELETE方式页面请求

一.JSON简介 JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式.易于人阅读和编写.同时也易于机器解析和生成.它基于JavaScript Programming Language, Standard ECMA-262 3rd Edition - December 1999的一个子集.JSON采用完全独立于语言的文本格式,但是也使用了类似于C语言家族的习惯(包括C, C++, C#, Java, JavaScript, Perl, Python等).这

网络请求数据 get请求方式 &nbsp; post请求 协议异步连接服务器 block异步连接服务器

网络请求三部 创建一个请求(添加接口,对接口进行解码,) 设定请求方式(将接口转为NSURL,设置请求[请求地址, 缓存策略, 超时时间],设置请求方式) 连接服务器([同步连接,异步连接]代理连接,block连接) #import "MainViewController.h" @interface MainViewController () @property (retain, nonatomic) IBOutlet UIImageView *ImageWiew; //get请求方法

Play framework框架中通过post方式发送请求

搞了好久这个最终还是在play官方文档中看见的发送请求的方式,国内好像很少有使用这个框架的,加之自己不是太愿意宣传,好东西总归是好东西,不说废话了. 在play中发送请求有两种常用的方式,一种get,一种post,当然,这里说的发送请求都是向第三方站点发送请求,而不是内部发送,内部当然不需要通过这种方式了. get方式: WS.url("url").setQueryParameter(arg0, arg1)..setQueryParameter(arg0, arg1).get(); 而

3、struts2 默认配置、数据处理的集中方式、请求数据封装、日期转换器

struts2 默认配置 1.全局视图跳转配置.配置的各项默认值 在config.xml中如此配置 <!-- 配置全局跳转视图 --> <global-results> <result name="success">/index.jsp</result> </global-results> <!-- 配置各项默认值 --> <!-- name 只配置了访问路径名称 class 默认执行的action在stru

ajax的get 和post方式发送请求

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getS

关于Ajax的type为post提交方式出现请求失效问题

最近碰到这样一个问题,原本一个ajax异步提交数据之前是很好的,很多系统都延用了均未出现任何问题.最近这个版本却出现ajax方式post数据不到后台程序,让我折腾了好几天.起初的ajax是这样写的: view sourceprint? 01.$.ajax({ 02.type: 'POST', 03.url: "/Ajax/SaveData.aspx", 04.dataType: "json", 05.data: "RequestTime="+ (