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 = ...
随机推荐
- -03-PetaLinux通过eMMC方式启动【Xilinx-Petalinux学习】
前面说的我的硬件上有一颗eMMC的芯片,型号是MTFC4GACAJCN-4M IT,有4GB的容量. BOOT.bin的文件较小,只有不到3MB,但是image.ub的文件根据不同的需求,将来可能会越 ...
- 如何优雅地发布Hexo博客
前言 就目前而言,我所知道的发布Hexo的博客有如下几种: 1.原始方式,也就是在服务器上编写md文件,然后利用hexo g来生成,详见:hexo从零开始到搭建完整: 2.利用github+hook来 ...
- 机器学习算法--svm实战
1.不平衡数据分类问题 对于非平衡级分类超平面,使用不平衡SVC找出最优分类超平面,基本的思想是,我们先找到一个普通的分类超平面,自动进行校正,求出最优的分类超平面 测试代码如下: import nu ...
- C++的const类成员函数
转自:http://blog.csdn.net/lihao21/article/details/8634876 我们知道,在C++中,若一个变量声明为const类型,则试图修改该变量的值的操作都被视编 ...
- 深入理解javascript之typeof和instanceof
1.https://blog.csdn.net/mevicky/article/details/50353881 (深入理解javascript之typeof和instanceof)
- gradle ssh 插件
org.hidetake.ssh Gradle SSH Plugin is a Gradle plugin which provides remote command execution and fi ...
- 将java打jar包成linux后台服务service
将java打jar包成linux后台服务service 第一步:将java程序打成jar包 build.gradle配置文件中加spring-boot-gradle-plugin插件,具体配置如下(配 ...
- VERSIONINFO Resource
转自(http://www.xuebuyuan.com/1202062.html) VERSIONINFO Resource Defines a version-information resourc ...
- SGU 141.Jumping Joe 数论,拓展欧几里得,二元不等式 难度:3
141. Jumping Joe time limit per test: 0.25 sec. memory limit per test: 4096 KB Joe is a frog who lik ...
- vue: alias
resolve: { extensions: ['.js', '.vue', '.json'], alias: { '@': path.resolve('src') } }