HttpHelp 请求帮助类
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq; namespace Share
{
public class HttpHelp
{
/// <summary>
/// url为请求的网址,param参数为需要查询的条件(服务端接收的参数,没有则为null)
/// </summary>
/// <param name="url"></param>
/// <param name="param"></param>
/// <returns></returns>
public static string Get(string url, Dictionary<string, string> param)
{
if (param != null) //有参数的情况下,拼接url
{
url = url + "?";
url = param.Aggregate(url, (current, item) => current + item.Key + "=" + item.Value + "&");
url = url.Substring(, url.Length - );
}
#region 写日记 LogHelp.WriteLog(url);
#endregion
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;//创建请求
request.Method = "GET"; //请求方法为GET
HttpWebResponse res; //定义返回的response
try
{
res = (HttpWebResponse)request.GetResponse(); //此处发送了请求并获得响应
}
catch (WebException ex)
{
res = (HttpWebResponse)ex.Response;
}
StreamReader sr = new StreamReader(res.GetResponseStream(), Encoding.UTF8);
string content = sr.ReadToEnd(); //响应转化为String字符串
return content;
}
//url为请求的网址,param为需要传递的参数
//返回服务端的额响应
/// <summary>
/// url为请求的网址,param为需要传递的参数
/// </summary>
/// <param name="url"></param>
/// <param name="param"></param>
/// <returns></returns>
public static string Post(string url, Dictionary<String, String> param)
{
#region 写日记
string parameterSt = "";
if (param.Count != ) //将参数添加到json对象中
{
foreach (var item in param)
{
parameterSt += "&" + item.Key + "=" + item.Value;
}
}
LogHelp.WriteLog(url + parameterSt);
#endregion HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; //创建请求
CookieContainer cookieContainer = new CookieContainer();
request.CookieContainer = cookieContainer;
request.AllowAutoRedirect = true;
//request.AllowReadStreamBuffering = true;
request.MaximumResponseHeadersLength = ;
request.Method = "POST"; //请求方式为post
request.AllowAutoRedirect = true;
request.MaximumResponseHeadersLength = ;
request.ContentType = "application/json";
JObject json = new JObject();
if (param.Count != ) //将参数添加到json对象中
{
foreach (var item in param)
{
json.Add(item.Key, item.Value);
}
}
string jsonstring = json.ToString();//获得参数的json字符串
byte[] jsonbyte = Encoding.UTF8.GetBytes(jsonstring);
Stream postStream = request.GetRequestStream();
postStream.Write(jsonbyte, , jsonbyte.Length);
postStream.Close();
//发送请求并获取相应回应数据
HttpWebResponse res;
try
{
res = (HttpWebResponse)request.GetResponse();
}
catch (WebException ex)
{
res = (HttpWebResponse)ex.Response;
}
StreamReader sr = new StreamReader(res.GetResponseStream(), Encoding.UTF8);
string content = sr.ReadToEnd(); //获得响应字符串
return content;
} //url为请求的网址,param为需要传递的参数
//返回服务端的额响应
/// <summary>
/// url为请求的网址,param为需要传递的参数
/// </summary>
/// <param name="url"></param>
/// <param name="param"></param>
/// <returns></returns>
public static string Post(string url, string jsonstring = "")
{
#region 写日记 LogHelp.WriteLog(url + jsonstring);
#endregion HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; //创建请求
CookieContainer cookieContainer = new CookieContainer();
request.CookieContainer = cookieContainer;
request.AllowAutoRedirect = true;
//request.AllowReadStreamBuffering = true;
request.MaximumResponseHeadersLength = ;
request.Method = "POST"; //请求方式为post
request.AllowAutoRedirect = true;
request.MaximumResponseHeadersLength = ;
request.ContentType = "application/json"; byte[] jsonbyte = Encoding.UTF8.GetBytes(jsonstring);
Stream postStream = request.GetRequestStream();
postStream.Write(jsonbyte, , jsonbyte.Length);
postStream.Close();
//发送请求并获取相应回应数据
HttpWebResponse res;
try
{
res = (HttpWebResponse)request.GetResponse();
}
catch (WebException ex)
{
res = (HttpWebResponse)ex.Response;
}
StreamReader sr = new StreamReader(res.GetResponseStream(), Encoding.UTF8);
string content = sr.ReadToEnd(); //获得响应字符串
return content;
} /// <summary>
/// HttpUploadFile 上传文件 HttpUploadFile("http://localhost/Test", new string[] { @"E:\Index.htm", @"E:\test.rar" }, data));
/// </summary>
/// <param name="url"></param>
/// <param name="files"></param>
/// <param name="data"></param>
/// <returns></returns>
public static string HttpUploadFile(string url, string[] files, Dictionary<string, string> param = null)
{
Encoding encoding = Encoding.UTF8;
string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
byte[] boundarybytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
byte[] endbytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n"); //1.HttpWebRequest
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.ContentType = "multipart/form-data; boundary=" + boundary;
request.Method = "POST";
request.KeepAlive = true;
request.Credentials = CredentialCache.DefaultCredentials; using (Stream stream = request.GetRequestStream())
{
//1.1 key/value
string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
if (param != null)
{
foreach (string key in param.Keys)
{
stream.Write(boundarybytes, , boundarybytes.Length);
string formitem = string.Format(formdataTemplate, key, param[key]);
byte[] formitembytes = encoding.GetBytes(formitem);
stream.Write(formitembytes, , formitembytes.Length);
}
} //1.2 file
string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: application/octet-stream\r\n\r\n";
byte[] buffer = new byte[];
int bytesRead = ;
for (int i = ; i < files.Length; i++)
{
stream.Write(boundarybytes, , boundarybytes.Length);
string header = string.Format(headerTemplate, "file" + i, Path.GetFileName(files[i]));
byte[] headerbytes = encoding.GetBytes(header);
stream.Write(headerbytes, , headerbytes.Length);
using (FileStream fileStream = new FileStream(files[i], FileMode.Open, FileAccess.Read))
{
while ((bytesRead = fileStream.Read(buffer, , buffer.Length)) != )
{
stream.Write(buffer, , bytesRead);
}
}
} //1.3 form end
stream.Write(endbytes, , endbytes.Length);
}
//2.WebResponse
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (StreamReader stream = new StreamReader(response.GetResponseStream()))
{
return stream.ReadToEnd();
} } /// <summary>
/// 文件下载
/// </summary>
/// <param name="url">抓取url</param>
/// <param name="filePath">保存文件名</param>
/// <param name="oldurl">来源路径</param>
/// <returns></returns>
public static void HttpDownloadFile(string url, string filePath)
{
try
{
HttpWebRequest Myrq = (HttpWebRequest)HttpWebRequest.Create(url); HttpWebResponse myrp = (HttpWebResponse)Myrq.GetResponse();
long totalBytes = myrp.ContentLength;
Stream st = myrp.GetResponseStream();
Stream so = new FileStream(filePath, FileMode.Create);
long totalDownloadedByte = ;
byte[] by = new byte[];
int osize = st.Read(by, , (int)by.Length);
while (osize > )
{
totalDownloadedByte = osize + totalDownloadedByte;
so.Write(by, , osize);
osize = st.Read(by, , (int)by.Length);
}
so.Close();
st.Close();
} catch (Exception ex)
{
LogHelp.WriteLog(ex.Message + ex.StackTrace);
}
}
}
}
用法:
public FindCabinetListRpModel FindCabinetList(FindCabinetListRt rt)
{
GetToken(rt);
ConvertHelp.NoProperties.Clear();
string parameterSt = ConvertHelp.GetProperties(rt);
Uri address = new Uri(_baseAddress + "/pickup/findCabinetList?" + parameterSt);
string rpJson = HttpHelp.Post(address.ToString()); try
{
//调用接口
var rpModel = JSONHelp.parse<FindCabinetListRpModel>(rpJson);
return rpModel;
}
catch (Exception ex)
{
throw ex;
}
}
HttpHelp 请求帮助类的更多相关文章
- WebUtils-网络请求工具类
网络请求工具类,大幅代码借鉴aplipay. using System; using System.Collections.Generic; using System.IO; using System ...
- Http、Https请求工具类
最近在做微信开发,使用http调用第三方服务API,有些是需要https协议,通过资料和自己编码,写了个支持http和https的工具类,经验证可用,现贴出来保留,也供需要的人使用(有不足的地方,也请 ...
- 微信https请求工具类
工作中用到的微信https请求工具类. package com.gxgrh.wechat.tools; import com.gxgrh.wechat.wechatapi.service.System ...
- HTTP请求工具类
HTTP请求工具类,适用于微信服务器请求,可以自测 代码; /// <summary> /// HTTP请求工具类 /// </summary> public class Ht ...
- Java请求参数类QueryParameter
import java.util.HashMap; import java.util.Map; import org.apache.commons.lang.StringUtils; /** * 请求 ...
- 实现一个简单的http请求工具类
OC自带的http请求用起来不直观,asihttprequest库又太大了,依赖也多,下面实现一个简单的http请求工具类 四个文件源码大致如下,还有优化空间 MYHttpRequest.h(类定义, ...
- 远程Get,Post请求工具类
1.远程请求工具类 import java.io.*; import java.net.URL; import java.net.URLConnection; import java.util.L ...
- C#实现的UDP收发请求工具类实例
本文实例讲述了C#实现的UDP收发请求工具类.分享给大家供大家参考,具体如下: 初始化: ListeningPort = int.Parse(ConfigurationManager.AppSetti ...
- ajax请求工具类
ajax的get和post请求工具类: /** * 公共方法类 * * 使用 变量名=function()定义函数时,如果在变量名前加var,则这个变量变成局部变量 */var Common = ...
随机推荐
- TED #04#
Christopher Ategeka: How adoption worked for me 1. I experienced all the negative effects of poverty ...
- js输出大段html文档简便方法
原文链接:https://zhidao.baidu.com/question/586477237.html 把要输出的html全部写在某个id中,然后复制过去,你想放多少都行 <script t ...
- 20145339顿珠达杰 《网络对抗技术》 逆向与Bof基础
目的 通过一些方法,使能够运行本不该被运行的代码部分,或得到shell的使用: 将正常运行代码部分某处call后的目标地址,修改为另一部分我们希望执行.却本不应该执行的代码部分首地址(这需要我们有一定 ...
- QT+VS中ui不能声明为指针?
问题描述:QtCreator里的UI全是默认为指针类型,调用的时候[ui->]但是使用VS+Qt来,发来默认的是变量类型,使用的时候[ui.] 统一:为了统一我把后者声明改为前者 问题:在mai ...
- HDU 6342 Expression in Memories(模拟)多校题解
题意:给你一个规则,问你写的对不对. 思路:规则大概概括为:不能出现前导零,符号两边必须是合法数字.我们先把所有问号改好,再去判断现在是否合法,这样判断比一边改一边判断容易想. 下面的讲解问号只改为+ ...
- SSL/TLS协议概览
SSL/TLS协议是什么 计算机网络的OSI七层模型和TCP/IP四层模型想必大家都知道.其中SSL/TLS是一种介与于传输层(比如TCP/IP)和应用层(比如HTTP)的协议.它通过"握手 ...
- hdu 5687 Problem C trie树
Problem C Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 131072/131072 K (Java/Others) Prob ...
- codeforces 356 div2 C.Bear and Prime 100 数学
C. Bear and Prime 100 time limit per test 1 second memory limit per test 256 megabytes input standar ...
- 100W数据,测试复合索引
复合索引不是那么容易被catch到的. 两个查询条件都是等于的时候,才会被catch到. mysql> select count(*) from tf_user_index where sex ...
- Postman模拟json传参
首先在headers中,设置Content-Type为applicationon/json,如图: 然后再body中,选择raw,写入json数据结构,如图: