/// <summary>
/// http请求类
/// </summary>
public class HttpHelper
{ private HttpClient _httpClient;
private string _baseIPAddress; /// <param name="ipaddress">请求的基础IP,例如:http://192.168.0.33:8080/ </param>
public HttpHelper(string ipaddress = "")
{
this._baseIPAddress = ipaddress;
_httpClient = new HttpClient { BaseAddress = new Uri(_baseIPAddress) };
} /// <summary>
/// 创建带用户信息的请求客户端
/// </summary>
/// <param name="userName">用户账号</param>
/// <param name="pwd">用户密码,当WebApi端不要求密码验证时,可传空串</param>
/// <param name="uriString">The URI string.</param>
public HttpHelper(string userName, string pwd = "", string uriString = "")
: this(uriString)
{
if (!string.IsNullOrEmpty(userName))
{
_httpClient.DefaultRequestHeaders.Authorization = CreateBasicCredentials(userName, pwd);
}
} /// <summary>
/// Get请求数据
/// /// <para>最终以url参数的方式提交</para>
/// <para>yubaolee 2016-3-3 重构与post同样异步调用</para>
/// </summary>
/// <param name="parameters">参数字典,可为空</param>
/// <param name="requestUri">例如/api/Files/UploadFile</param>
/// <returns></returns>
public string Get(Dictionary<string, string> parameters, string requestUri)
{
if (parameters != null)
{
var strParam = string.Join("&", parameters.Select(o => o.Key + "=" + o.Value));
requestUri = string.Concat(ConcatURL(requestUri), '?', strParam);
}
else
{
requestUri = ConcatURL(requestUri);
} var result = _httpClient.GetStringAsync(requestUri);
return result.Result;
} /// <summary>
/// Get请求数据
/// <para>最终以url参数的方式提交</para>
/// </summary>
/// <param name="parameters">参数字典</param>
/// <param name="requestUri">例如/api/Files/UploadFile</param>
/// <returns>实体对象</returns>
public T Get<T>(Dictionary<string, string> parameters, string requestUri) where T : class
{
string jsonString = Get(parameters, requestUri);
if (string.IsNullOrEmpty(jsonString))
return null; return JsonHelper.Instance.Deserialize<T>(jsonString);
} /// <summary>
/// 以json的方式Post数据 返回string类型
/// <para>最终以json的方式放置在http体中</para>
/// </summary>
/// <param name="entity">实体</param>
/// <param name="requestUri">例如/api/Files/UploadFile</param>
/// <returns></returns>
public string Post(object entity, string requestUri)
{
string request = string.Empty;
if (entity != null)
//将对象转换成字节码
request = JsonHelper.Instance.Serialize(entity);
HttpContent httpContent = new StringContent(request);
//请求的头文件
httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
return Post(requestUri, httpContent);
} /// <summary>
/// 提交字典类型的数据
/// <para>最终以formurlencode的方式放置在http体中</para>
/// <para></para>
/// </summary>
/// <returns>System.String.</returns>
public string PostDicObj(Dictionary<string, object> para, string requestUri)
{
Dictionary<string, string> temp = new Dictionary<string, string>();
foreach (var item in para)
{
if (item.Value != null)
{
if (item.Value.GetType().Name.ToLower() != "string")
{
temp.Add(item.Key, JsonHelper.Instance.Serialize(item.Value));
}
else
{
temp.Add(item.Key, item.Value.ToString());
}
}
else {
temp.Add(item.Key, "");
}
} return PostDic(temp, requestUri);
} /// <summary>
/// Post Dic数据
/// <para>最终以formurlencode的方式放置在http体中</para>
/// <para></para>
/// </summary>
/// <returns>System.String.</returns>
public string PostDic(Dictionary<string, string> temp, string requestUri)
{
HttpContent httpContent = new FormUrlEncodedContent(temp);
httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
return Post(requestUri, httpContent);
} public string PostByte(byte[] bytes, string requestUrl)
{
HttpContent content = new ByteArrayContent(bytes);
content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
return Post(requestUrl, content);
} private string Post(string requestUrl, HttpContent content)
{
var result = _httpClient.PostAsync(ConcatURL(requestUrl), content);
return result.Result.Content.ReadAsStringAsync().Result;
} /// <summary>
/// 把请求的URL相对路径组合成绝对路径
/// <para></para>
/// </summary>
private string ConcatURL(string requestUrl)
{
return new Uri(_httpClient.BaseAddress, requestUrl).OriginalString;
} private AuthenticationHeaderValue CreateBasicCredentials(string userName, string password)
{
string toEncode = userName + ":" + password;
// The current HTTP specification says characters here are ISO-8859-1.
// However, the draft specification for the next version of HTTP indicates this encoding is infrequently
// used in practice and defines behavior only for ASCII.
Encoding encoding = Encoding.GetEncoding("utf-8");
byte[] toBase64 = encoding.GetBytes(toEncode);
string parameter = Convert.ToBase64String(toBase64); return new AuthenticationHeaderValue("Basic", parameter);
}
}

HttpClient的帮助类的更多相关文章

  1. android6.0SDK 删除HttpClient的相关类的解决方法

    本文转载自博客:http://blog.csdn.net/yangqingqo/article/details/48214865 android6.0SDK中删除HttpClient的相关类的解决方法 ...

  2. 在android 6.0(API 23)中,Google已经移除了移除了Apache HttpClient相关的类

    推荐使用HttpUrlConnection,如果要继续使用需要Apache HttpClient,需要在eclipse下libs里添加org.apache.http.legacy.jar,androi ...

  3. android 6.0 SDK中删除HttpClient的相关类的解决方法

    一.出现的情况 在eclipse或 android studio开发, 设置android SDK的编译版本为23时,且使用了httpClient相关类的库项目:如android-async-http ...

  4. httpclient pool帮助类

    摘自爬虫类  用于频繁请求减少网络消耗 import java.io.IOException; import java.io.InterruptedIOException; import java.i ...

  5. HttpClient封装工具类

    import java.io.IOException; import java.net.URI; import java.util.ArrayList; import java.util.List; ...

  6. HttpClient 通信工具类

    package com.taotao.web.service; import java.util.ArrayList; import java.util.List; import java.util. ...

  7. webrequest、httpwebrequest、webclient、HttpClient 四个类的区别

    一.在 framework 开发环境下: webrequest.httpwebreques  都是基于Windows Api 进行包装, webclient 是基于webrequest 进行包装:(经 ...

  8. HttpClient请求工具类

    package com.yangche.utils; import org.apache.http.NameValuePair; import org.apache.http.client.Clien ...

  9. Android 6.0删除Apache HttpClient相关类的解决方法

    相应的官方文档如下: 上面文档的大致意思是,在Android 6.0(API 23)中,Google已经移除了Apache HttpClient相关的类,推荐使用HttpUrlConnection. ...

随机推荐

  1. crud树型结构数据

    小型数据,比如标签,部门之类的,可以组织数据,成层状结构,一并返回前端,节省请求次数:但是大型数据,比如省市区等等联动,如果一并返回组织好的数据,查询量大,页面多次刷新,恶意请求,放入缓存还可以,其实 ...

  2. 【Go】 Go 语言环境安装

    安装环境/工具 1.Linux(CentOS 7.4版) 2.go1.11.2.linux-amd64.tar Go 语言环境安装 1.下载安装包 安装包下载地址为:https://golang.or ...

  3. python学习 day3 (3月4日)---字符串

    字符串: 下标(索引) 切片[起始:终止] 步长[起始:终止:1] 或者-1 从后往前 -1 -2 -3 15个专属方法: 1-6  : 格式:大小写 , 居中(6) s.capitalize() s ...

  4. ubuntu安装rubyOnRails

    https://gorails.com/setup/ubuntu/16.04#ruby-rbenv 文章很详细

  5. Maven手动将jar包放入本地仓库

    mvn install:install-file -Dfile=jar包的位置 -DgroupId=上面的groupId -DartifactId=上面的artifactId -Dversion=上面 ...

  6. 41.App 框架的搭建思路以及代码的规范

    本链接  引用别人文章https://www.jianshu.com/p/d553096914ff

  7. FASTDFS 安装与开发

    FASTDFS介绍 FastDFS开源地址:https://github.com/happyfish100 简介 FastDFS 是一个开源的高性能分布式文件系统(DFS). 它的主要功能包括:文件存 ...

  8. 使用bat批处理文件定时自动备份oracle数据库并上传ftp服务器

    一.使用bat批处理文件备份oracle(前提是配置好oracle数据库客户端) @echo off set databasename=orcl  //数据库名 set username=ninic ...

  9. confluence5.65+CentOS+mysql安装破解

    以atlassian-confluence-5.6.5为例   先安装JAVA环境         通过yum安装jdk,5.6.5不支持jdk1.8,所以安装1.7或者1.6都可以         ...

  10. 实战fortran77基础语法2

    由于大量的接触fortran77,先学习fortran77吧 1.fortran不区分大小写,fortran77一般全部大写,感觉没必要,不好读,还是用大小写混合着写吧.后缀 .for 为固定格式的代 ...