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 请求帮助类的更多相关文章

  1. WebUtils-网络请求工具类

    网络请求工具类,大幅代码借鉴aplipay. using System; using System.Collections.Generic; using System.IO; using System ...

  2. Http、Https请求工具类

    最近在做微信开发,使用http调用第三方服务API,有些是需要https协议,通过资料和自己编码,写了个支持http和https的工具类,经验证可用,现贴出来保留,也供需要的人使用(有不足的地方,也请 ...

  3. 微信https请求工具类

    工作中用到的微信https请求工具类. package com.gxgrh.wechat.tools; import com.gxgrh.wechat.wechatapi.service.System ...

  4. HTTP请求工具类

    HTTP请求工具类,适用于微信服务器请求,可以自测 代码; /// <summary> /// HTTP请求工具类 /// </summary> public class Ht ...

  5. Java请求参数类QueryParameter

    import java.util.HashMap; import java.util.Map; import org.apache.commons.lang.StringUtils; /** * 请求 ...

  6. 实现一个简单的http请求工具类

    OC自带的http请求用起来不直观,asihttprequest库又太大了,依赖也多,下面实现一个简单的http请求工具类 四个文件源码大致如下,还有优化空间 MYHttpRequest.h(类定义, ...

  7. 远程Get,Post请求工具类

    1.远程请求工具类   import java.io.*; import java.net.URL; import java.net.URLConnection; import java.util.L ...

  8. C#实现的UDP收发请求工具类实例

    本文实例讲述了C#实现的UDP收发请求工具类.分享给大家供大家参考,具体如下: 初始化: ListeningPort = int.Parse(ConfigurationManager.AppSetti ...

  9. ajax请求工具类

    ajax的get和post请求工具类: /** * 公共方法类 *  * 使用  变量名=function()定义函数时,如果在变量名前加var,则这个变量变成局部变量 */var Common = ...

随机推荐

  1. MySQL事务概述-1

    事务是数据库区别于文件系统最重要的特性之一.事务可由一条非常简单的SQL语句组成,也可以由一组复杂的SQL语句组成.事务是访问并更新数据库中各种数据项的一个程序执行单元.在事务操作中,要么都做修改,要 ...

  2. 20155201 实验四《Java面向对象程序设计》实验报告

    20155201 实验四<Java面向对象程序设计>实验报告 一.实验内容 1.基于Android Studio开发简单的Android应用并部署测试; 2.了解Android.组件.布局 ...

  3. sqlite的缺点和限制

    随着查询变大变复杂,查询时间使得网络调用或者事务处理开销相形见绌, 这时一些大型的设计复杂的数据库开始发挥作用了. 虽然SQLite也能处理复杂的查询,但是它没有精密的优化器或者查询计划器. SQLi ...

  4. ZooKeeper增加Observer部署模式提高性能(转)

    除了Leader和Follow模式之外,还有第三种模式:Observer模式. Observer:在不伤害写性能的情况下扩展ZooKeeper. 虽然通过Client直接连接到ZooKeeper集群的 ...

  5. UVa 11552 最小的块数(序列划分模型:状态设计)

    https://vjudge.net/problem/UVA-11552 题意:输入一个正整数k和字符串S,字符串的长度保证为k的倍数.把S的字符按照从左到右的顺序每k个分成一组,每组之间可以任意重排 ...

  6. UVa 10054 项链(欧拉回路)

    https://vjudge.net/problem/UVA-10054 题意:有一种由彩色珠子连接成的项链.每个珠子的两半由不同颜色组成.相邻两个珠子在接触的地方颜色相同.现在有一些零碎的珠子,需要 ...

  7. Qt5.4.1_静态编译

    http://www.cnblogs.com/findumars/p/4852350.html http://godebug.org/index.php/archives/133/ http://ww ...

  8. vue-router详解

    对于单页应用,官方提供了vue-router进行路由跳转的处理,本篇主要也是基于其官方文档写作而成. 安装 基于传统,我更喜欢采用npm包的形式进行安装. npm install vue-router ...

  9. Linux编写一个C程序HelloWorld

    环境 需要文本编辑器和编译器,文本编辑器用linux(我用的centos7)自带的vi,编译器用gcc(GNU C Compiler/GNU Compiler Collection) 安装gcc,查看 ...

  10. HDU - 4812 D Tree 点分治

    http://acm.hdu.edu.cn/showproblem.php?pid=4812 题意:有一棵树,每个点有一个权值要求找最小的一对点,路径上的乘积mod1e6+3为k 题解:点分治,挨个把 ...