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. python3的一些练习题

    下面是最近写的一些python3版本的一些练习题: 1.4+44+444+4444+.....+=? root@wadeson:~/study_for_python/homework# cat aa. ...

  2. 20145326 《Java程序设计》第10周学习总结

    教材学习内容总结 网络编程 •网络编程就是在两个或两个以上的设备(例如计算机)之间传输数据. •程序员所作的事情就是把数据发送到指定的位置,或者接收到指定的数据,这个就是狭义的网络编程范畴. •在发送 ...

  3. HeyWeGo第五周项目总结

    HeyWeGo第五周项目总结 项目内容 使用java程序开发一款扫雷游戏 游戏项目规划: 确定游戏中方块格子的个数 确定游戏中地雷的个数(初始10个),完成布雷 计算每个方块周围的雷数,在方块周围本身 ...

  4. linux下 ip指令

    目录 Network ip command Command :ip 简介 内容 Network ip command Command :ip 简介 ip 是個指令喔!並不是那個 TCP/IP 的 IP ...

  5. 使用webuploader实现文件的断点续传

    webuploader是百度Fex团队开发的一款上传插件,对于现代浏览器采用了HTML5的方式进行上传,二为了兼容IE浏览器则采用了Flash的方式作为补充. 首先,这个插件在全局仅暴露一个WebUp ...

  6. AI病毒来袭,拿什么拯救你我的电脑?

    文|雷宇 来源|智能相对论(aixdlun) 在刘慈欣的科幻小说<中国2185>中,除领土,领海,领空外,还有一个被称为电子领土的地方,这个地方除了容易受常规武器破坏外,还容易受到软件武器 ...

  7. java中字面量,常量和变量之间的区别(附:Integer缓存机制)

    一.引子 在各种教科书和博客中这三者经常被引用,今天复习到内存区域,想起常量池中就是存着字面量和符号引用,其实这三者并不是只在java中才有,各个语言中都有类似的定义,所以做一下总结,以示区分. 二. ...

  8. 小图标变为字体@font-face

    https://www.zhihu.com/question/29054543 https://icomoon.io/app/#/select http://iconfont.cn/

  9. Python str 与 bytes 类型 之间的转换

    bytes:字节数组,通常用它可以描述 “一个字符串”,只不过该字符串是  “bytes类型”,所以容易与str类型混淆,他们二者之间的转换: https://blog.csdn.net/lanchu ...

  10. Android Studio 中删除项目和项目找回------ Project Structure的使用

    删除项目 点击File——Project Structure 在Project Structure页面,选中要删除的项目,点击上面的减号图标. 我把两个一起删除了,再次打开时,啥也没有 如果想要把不要 ...