后台web请求代码(含https,json提交)
后台web请求
namespace XXXX.Utilites
{
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text; public class PostHttpResponse
{
#region Static Field
private static readonly string DefaultUserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";
#endregion #region public Method
public static string PostHttpResponseJson(string url)
{
string json = string.Empty;
Encoding encoding = Encoding.UTF8;
HttpWebResponse Response = CreatePostHttpResponseJson(url,null,null, null, null, encoding, null);
json = GetStream(Response, encoding);
return json;
} public static string PostHttpResponseJson(string url, string postJson)
{
string json = string.Empty;
Encoding encoding = Encoding.UTF8;
HttpWebResponse Response = CreatePostHttpResponseJson(url, postJson, null, null, null, encoding, null);
json = GetStream(Response, encoding);
return json;
} /// <summary>
/// 创建POST方式Json数据的HTTP请求(包括了https站点请求)
/// </summary>
/// <param name="url">请求的URL</param>
/// <param name="parameters">随同请求POST的参数名称及参数值字典</param>
/// <param name="timeout">请求的超时时间</param>
/// <param name="userAgent">请求的客户端浏览器信息,可以为空</param>
/// <param name="requestEncoding">发送HTTP请求时所用的编码</param>
/// <param name="cookies">随同HTTP请求发送的Cookie信息,如果不需要身份验证可以为空</param>
/// <returns></returns>
public static HttpWebResponse CreatePostHttpResponseJson(string url, string postJson,string parameters, int? timeout, string userAgent, Encoding requestEncoding, string referer)
{
if (string.IsNullOrEmpty(url))
{
throw new ArgumentNullException("url");
}
if (requestEncoding == null)
{
throw new ArgumentNullException("requestEncoding");
} HttpWebRequest request = null;
//如果是发送HTTPS请求
if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
{
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
request = WebRequest.Create(url) as HttpWebRequest;
request.ProtocolVersion = HttpVersion.Version10;
}
else
{
request = WebRequest.Create(url) as HttpWebRequest;
} request.Method = "POST";
//服务端 判断 客户端 提交的是否是 JSON数据 时
request.ContentType = "application/json;charset=UTF-8";
request.KeepAlive = true; if (!string.IsNullOrEmpty(userAgent))
{
request.UserAgent = userAgent;
}
else
{
request.UserAgent = DefaultUserAgent;
} if (timeout.HasValue)
{
request.Timeout = timeout.Value;
} //如果需要POST数据
#region post parameter 类似querystring格式
if (parameters != null)
{
byte[] data = requestEncoding.GetBytes(parameters);
using (Stream stream = request.GetRequestStream())
{
stream.Write(data, , data.Length);
stream.Close();
}
}
#endregion #region post json
if (!string.IsNullOrEmpty(postJson))
{
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
//string json = "{\"user\":\"test\"," +
// "\"password\":\"bla\"}"; streamWriter.Write(postJson);
streamWriter.Flush();
streamWriter.Close();
}
}
#endregion if (!string.IsNullOrEmpty(referer))
{
request.Referer = referer;
} HttpWebResponse response = request.GetResponse() as HttpWebResponse; if (request.CookieContainer != null)
{
response.Cookies = request.CookieContainer.GetCookies(request.RequestUri);
} return response;
} #endregion #region Private Method
private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
{
return true; //总是接受
} /// <summary>
/// 将response转换成文本
/// </summary>
/// <param name="response"></param>
/// <param name="encoding"></param>
/// <returns></returns>
private static string GetStream(HttpWebResponse response, Encoding encoding)
{
try
{
if (response.StatusCode == HttpStatusCode.OK)
{
switch (response.ContentEncoding.ToLower())
{
case "gzip":
{
string result = Decompress(response.GetResponseStream(), encoding);
response.Close();
return result;
}
default:
{
using (StreamReader sr = new StreamReader(response.GetResponseStream(), encoding))
{
string result = sr.ReadToEnd();
sr.Close();
sr.Dispose();
response.Close();
return result;
}
}
}
}
else
{
response.Close();
}
}
catch (Exception e)
{
throw e;
}
return "";
} private static string Decompress(Stream stream, Encoding encoding)
{
byte[] buffer = new byte[];
//int length = 0; using (GZipStream gz = new GZipStream(stream, CompressionMode.Decompress))
{
//GZipStream gzip = new GZipStream(res.GetResponseStream(), CompressionMode.Decompress);
using (StreamReader reader = new StreamReader(gz, encoding))
{
return reader.ReadToEnd();
}
/*
using (MemoryStream msTemp = new MemoryStream())
{
//解压时直接使用Read方法读取内容,不能调用GZipStream实例的Length等属性,否则会出错:System.NotSupportedException: 不支持此操作;
while ((length = gz.Read(buffer, 0, buffer.Length)) != 0)
{
msTemp.Write(buffer, 0, length);
} return encoding.GetString(msTemp.ToArray());
}
* */
}
} #endregion
}
}
后台web请求代码(含https,json提交)的更多相关文章
- Postman中添加真实请求(Chrome Networks中的全部请求,含https)copy as har
Postman中添加真实请求(Chrome Networks中的全部请求,含https) xyxzfj 关注 2018.05.22 19:44* 字数 559 阅读 1176评论 0喜欢 0 Post ...
- Android开发之开源框架OKHTTP的Get请求代码,得到json字符串方法
<span style="white-space:pre"> </span><pre name="code" class=&q ...
- 解决Ajax请求后台Servlet接口拿不到JSON数据问题
前端Ajax请求代码如下: window.onload=function() { var url='http://127.0.0.1:8080/testpj/ErrorlogServlet'; $.a ...
- aes加解密后续问题contentType不是application/json时候后台解析请求对象request
一.post请求的三种content-type 1.application/x-www-form-urlencoded 主要用于如下:1.1: 最常见的POST提交数据方式.1.2:原生form默认的 ...
- ANTS Performance Profiler 8:支持对Web请求、异步代码和WinRT的性能剖析
下载与激活:http://download.csdn.net/detail/lone112/6734291 离线激活 位于英国的Red Gate Software有限公司最近发布了ANTS Per ...
- Jsoup请求http或https返回json字符串工具类
Jsoup请求http或https返回json字符串工具类 所需要的jar包如下: jsoup-1.8.1.jar 依赖jar包如下: httpclient-4.5.4.jar; httpclient ...
- java post请求的表单提交和json提交简单小结
在java实现http请求时有分为多种参数的传递方式,以下给出通过form表单提交和json提交的参数传递方式: public String POST_FORM(String url, Map< ...
- 爬取百度页面代码写入到文件+web请求过程解析
一.爬取百度页面代码写入到文件 代码示例: from urllib.request import urlopen #导入urlopen包 url="http://www.baidu.com& ...
- 与JavaWeb有关的故事(web请求与Java I/O)
作为一名后端屌丝程序员,对算法.并发.性能乐此不疲.但是,随着年龄和阅历的增加,显然叶落而不知秋的心态是不太能混了.尤其是,某T面试官在明知我是后端,且明确表示对HTTP协议不太熟的情况下,强行让我解 ...
随机推荐
- Azkaban任务流编写
在Azkaban中,一个project包含一个或多个flows,一个flow包含多个job.job是你想在azkaban中运行的一个进程,可以是Command,也可以是一个Hadoop任务.当然,如果 ...
- 1021 docker初识
docker与虚拟机相比,没有虚拟化内核,转而使用宿主机的内核.因此docker更轻更快 docker缺点:后端兼容性测试需求.把软件安装在不同的操作系统上进行测试,观察软件运行是否良好. 不能用do ...
- CentOS–root密码忘记的解决办法
一.重启系统,如图:GRUB: 在引导装载程序菜单上,用上下方向键选择你忘记密码的那个系统键入“e” 来进入编辑模式. 2.接下来你可以看到如下图所示的画面,然后你再用上下键选择最新的内核(这里 ...
- PHP生产二维码
1.引入phpqrcode包 <?php include 'phpqrcode.php'; QRcode::png('http://www.learnphp.cn',"code.png ...
- C# 进程(应用程序)间通信
SendMessage用法: 函数功能:该函数将指定的消息发送到一个或多个窗口.此函数为指定的窗口调用窗口程序,直到窗口程序处理完消息再返回.该函数是应用程序和应用程序之间进行消息传递的主要手段之一. ...
- mac下yii安装
下载https://github.com/yiisoft/yii2-app-advanced/releases,里边没index.php文件 1.http://www.yiichina.com/que ...
- 随机分布 + action 计数
For random samples from , use: 注意平方: sigma * np.random.randn(...) + mu 2.5*2.5 = 6.25 Two-by-four a ...
- centos7 单台zookeeper安装
1.创建 /usr/local/services/zookeeper 文件夹: mkdir -p /usr/local/services/zookeeper 2.进入到 /usr/local/ser ...
- 如何用Python实现常见机器学习算法-4
四.SVM支持向量机 1.代价函数 在逻辑回归中,我们的代价为: 其中: 如图所示,如果y=1,cost代价函数如图所示 我们想让,即z>>0,这样的话cost代价函数才会趋于最小(这正是 ...
- DevExpress,LayoutControl,TreeList,GridControl等
1.显示边框进行折叠 选择一个layoutControlGroupX 将其GroupBordersVisible设置成True,将TextVisiable=True 2. TreeList 2.1需要 ...