HttpClientHelper
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization; namespace SXYC.Common
{
public class HttpClientHelpClass
{
/// <summary>
/// get请求
/// </summary>
/// <param name="url"></param>
/// <returns></returns>
public static string GetResponse(string url, out string statusCode)
{
if (url.StartsWith("https"))
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls; var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = httpClient.GetAsync(url).Result;
statusCode = response.StatusCode.ToString();
if (response.IsSuccessStatusCode)
{
string result = response.Content.ReadAsStringAsync().Result;
return result;
}
return null;
} public static string RestfulGet(string url)
{
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
// Get response
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
// Get the response stream
StreamReader reader = new StreamReader(response.GetResponseStream());
// Console application output
return reader.ReadToEnd();
}
} public static T GetResponse<T>(string url)
where T : class, new()
{
if (url.StartsWith("https"))
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls; var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = httpClient.GetAsync(url).Result; T result = default(T); if (response.IsSuccessStatusCode)
{
Task<string> t = response.Content.ReadAsStringAsync();
string s = t.Result; result = JsonConvert.DeserializeObject<T>(s);
}
return result;
} /// <summary>
/// post请求
/// </summary>
/// <param name="url"></param>
/// <param name="postData">post数据</param>
/// <returns></returns>
public static string PostResponse(string url, string postData, out string statusCode)
{
if (url.StartsWith("https"))
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls; HttpContent httpContent = new StringContent(postData);
httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
httpContent.Headers.ContentType.CharSet = "utf-8"; HttpClient httpClient = new HttpClient();
//httpClient..setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8"); HttpResponseMessage response = httpClient.PostAsync(url, httpContent).Result; statusCode = response.StatusCode.ToString();
if (response.IsSuccessStatusCode)
{
string result = response.Content.ReadAsStringAsync().Result;
return result;
} return null;
} /// <summary>
/// 发起post请求
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="url">url</param>
/// <param name="postData">post数据</param>
/// <returns></returns>
public static T PostResponse<T>(string url, string postData)
where T : class, new()
{
if (url.StartsWith("https"))
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls; HttpContent httpContent = new StringContent(postData);
httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
HttpClient httpClient = new HttpClient(); T result = default(T); HttpResponseMessage response = httpClient.PostAsync(url, httpContent).Result; if (response.IsSuccessStatusCode)
{
Task<string> t = response.Content.ReadAsStringAsync();
string s = t.Result; result = JsonConvert.DeserializeObject<T>(s);
}
return result;
} /// <summary>
/// 异步post请求
/// </summary>
/// <param name="url"></param>
/// <param name="jsonParam"></param>
/// <param name="encode"></param>
/// <param name="dic"></param>
/// <returns></returns>
public async static Task<string> PostJsonAsync(string url, string jsonParam, string encode, Dictionary<string, string> dic)
{
using (var client = new HttpClient())
{
foreach (KeyValuePair<string, string> item in dic)
{
client.DefaultRequestHeaders.Add(item.Key, item.Value);
}
// string strDecodeBody = HttpUtility.UrlEncode(jsonParam);
HttpContent content = new StringContent(jsonParam);
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
var response = await client.PostAsync(url, content); var responseString = await response.Content.ReadAsStringAsync();
return responseString;
}
} /// <summary>
/// 反序列化Xml
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="xmlString"></param>
/// <returns></returns>
public static T XmlDeserialize<T>(string xmlString)
where T : class, new()
{
try
{
XmlSerializer ser = new XmlSerializer(typeof(T));
using (StringReader reader = new StringReader(xmlString))
{
return (T)ser.Deserialize(reader);
}
}
catch (Exception ex)
{
throw new Exception("XmlDeserialize发生异常:xmlString:" + xmlString + "异常信息:" + ex.Message);
} } public static string PostResponse(string url, string postData, string token, string appId, string serviceURL, out string statusCode)
{
if (url.StartsWith("https"))
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls; HttpContent httpContent = new StringContent(postData);
httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
httpContent.Headers.ContentType.CharSet = "utf-8"; httpContent.Headers.Add("token", token);
httpContent.Headers.Add("appId", appId);
httpContent.Headers.Add("serviceURL", serviceURL); HttpClient httpClient = new HttpClient();
//httpClient..setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8"); HttpResponseMessage response = httpClient.PostAsync(url, httpContent).Result; statusCode = response.StatusCode.ToString();
if (response.IsSuccessStatusCode)
{
string result = response.Content.ReadAsStringAsync().Result;
return result;
} return null;
} /// <summary>
/// 修改API
/// </summary>
/// <param name="url"></param>
/// <param name="postData"></param>
/// <returns></returns>
public static string KongPatchResponse(string url, string postData)
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.ContentType = "application/x-www-form-urlencoded";
httpWebRequest.Method = "PATCH"; byte[] btBodys = Encoding.UTF8.GetBytes(postData);
httpWebRequest.ContentLength = btBodys.Length;
httpWebRequest.GetRequestStream().Write(btBodys, , btBodys.Length); HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
var streamReader = new StreamReader(httpWebResponse.GetResponseStream());
string responseContent = streamReader.ReadToEnd(); httpWebResponse.Close();
streamReader.Close();
httpWebRequest.Abort();
httpWebResponse.Close(); return responseContent;
} /// <summary>
/// 创建API
/// </summary>
/// <param name="url"></param>
/// <param name="postData"></param>
/// <returns></returns>
public static string KongAddResponse(string url, string postData)
{
if (url.StartsWith("https"))
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
HttpContent httpContent = new StringContent(postData);
httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded") { CharSet = "utf-8" };
var httpClient = new HttpClient();
HttpResponseMessage response = httpClient.PostAsync(url, httpContent).Result;
if (response.IsSuccessStatusCode)
{
string result = response.Content.ReadAsStringAsync().Result;
return result;
}
return null;
} /// <summary>
/// 删除API
/// </summary>
/// <param name="url"></param>
/// <returns></returns>
public static bool KongDeleteResponse(string url)
{
if (url.StartsWith("https"))
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls; var httpClient = new HttpClient();
HttpResponseMessage response = httpClient.DeleteAsync(url).Result;
return response.IsSuccessStatusCode;
} /// <summary>
/// 删除API
/// </summary>
/// <param name="url"></param>
/// <returns></returns>
public static Task<string> Delete(string url, Dictionary<string, string> dic)
{
if (url.StartsWith("https"))
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls; using (var client = new HttpClient())
{
foreach (KeyValuePair<string, string> item in dic)
{
client.DefaultRequestHeaders.Add(item.Key, item.Value);
} HttpResponseMessage response = client.DeleteAsync(url).Result;
return Task.Run(() =>
{
return response.StatusCode.ToString();
});
} } /// <summary>
/// 修改或者更改API
/// </summary>
/// <param name="url"></param>
/// <param name="postData"></param>
/// <returns></returns>
public static string KongPutResponse(string url, string postData)
{
if (url.StartsWith("https"))
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls; HttpContent httpContent = new StringContent(postData);
httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded") { CharSet = "utf-8" }; var httpClient = new HttpClient();
HttpResponseMessage response = httpClient.PutAsync(url, httpContent).Result;
if (response.IsSuccessStatusCode)
{
string result = response.Content.ReadAsStringAsync().Result;
return result;
}
return null;
} /// <summary>
/// 检索API
/// </summary>
/// <param name="url"></param>
/// <returns></returns>
public static string KongSerchResponse(string url)
{
if (url.StartsWith("https"))
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls; var httpClient = new HttpClient();
HttpResponseMessage response = httpClient.GetAsync(url).Result;
if (response.IsSuccessStatusCode)
{
string result = response.Content.ReadAsStringAsync().Result;
return result;
}
return null;
}
}
}
HttpClientHelper的更多相关文章
- C#微信开发之旅(二):基础类之HttpClientHelper(更新:SSL安全策略)
public class HttpClientHelper 2 { 3 /// <summary> 4 /// get请求 5 ...
- C# HttpClientHelper请求
public class HttpClientHelper { /// <summary> /// get请求 /// </summary> /// <param nam ...
- java HttpClientHelper
1 首先配置pom.xml,具体参考我的这篇文章:使用httpclient需要的maven依赖 2 上代码 import java.io.IOException; import java.io.Inp ...
- 使用HttpClient的优解
新工作入职不满半周,目前仍然还在交接工作,适应环境当中,笔者不得不说看别人的源码实在是令人痛苦.所幸今天终于将大部分工作流畅地看了一遍,接下来就是熟悉框架技术的阶段了. 也正是在看源码的过程当中,有一 ...
- 又一种XML的解析方法
[Fact(DisplayName="用户名为空")] public void Should_UsernameEmpty() { var paras = new Dictionar ...
- windows phone 8.1教务在线客户端(后续)
经过了一番折腾,这个wp教务在线算是告一段落了,其实原理很简单,就是post方式访问登陆页面返回cookie,然后带着这个cookie用get方式继续访问你想要访问并取回内容的页面,而且httpcli ...
- WebApi 登录身份验证
前言:Web 用户的身份验证,及页面操作权限验证是B/S系统的基础功能,一个功能复杂的业务应用系统,通过角色授权来控制用户访问,本文通过Form认证,Mvc的Controller基类及Action的权 ...
- RESTLET开发实例
1 前提 由于近期工作的需要,要把RESTLET应用到项目中,于是在网上参考了一些资料的基础上,实践了一个关于RESTLET接口的小例子. Restlet的思想是:HTTP客户端与HTTP服务器之间的 ...
- android httpClient 支持HTTPS的2种处理方式
摘自: http://www.kankanews.com/ICkengine/archives/9634.shtml 项目中Android https或http请求地址重定向为HTTPS的地址,相信很 ...
随机推荐
- eclipse遇到启动报an error has occurred see the log file错
错误: 修改eclipse安装目录下比如D:\eclipse\configuration\.settings\org.eclipse.ui.ide.prefs, 删除 RECENT_WORKSPACE ...
- Maths | 病态问题和条件数
目录 1. 概念定义 1.1. 病态/ 良态问题 1.2. 适定/ 非适定问题 1.3. 良态/ 病态矩阵和条件数 2. 病态的根源 3. 计算条件数的方法 3.1. 与特征值的关系 3.2. 与奇异 ...
- 重装win10+ubuntu 双系统 UEFI启动模式
有较强的时效性!!先看一眼日期是否太古老! 任务 卸载双系统中的Ubuntu14,安装Ubuntu16 环境 操作系统: Win10 + Ubuntu14双系统 硬盘: 固态硬盘 + 机械硬盘,电脑的 ...
- scrapy的入门使用(一)
1. scrapy项目实现流程 创建一个scrapy项目:scrapy startproject mySpider 生成一个爬虫:scrapy genspider 提取数据:完善spider,使用x ...
- Exp8 Web基础 20154320 李超
1.实验后回答问题 (1)什么是表单. 表单是一个包含表单元素的区域,表单元素是允许用户在表单中输入信息的元素,表单在网页中主要负责数据采集功能,一个表单有三个基本组成部分:表单标签.表单域.表单按钮 ...
- UE4物理动画使用
Rigid Body Body的创建. 对重要骨骼创建Body,保证Body控制的是表现和变化比较大的骨骼. 需要对Root创建Body并绑定,设置为Kinematic且不启用物理.原因是UPrimi ...
- OC对象,自动释放池,OC与C语言的区别
在C语言中,编程都是面向过程的编程,每一个代码块都严格按照从上至下的顺序执行,在代码块之间同样也是这样, 但是在OC中往往不是这样,OC和C++.java等语言一样,都是面向对象的编程语言,在代码的执 ...
- 了解AOP
Spring AOP的实现是基于JAVA的代理机制, 从JDK1.3开始就支持代理功能, 但是性能成为一个很大问题, 为了解决JDK代理性能问题, 出现了CGLIB代理机制.它可以生成字节码, 所以它 ...
- Python之路【第五篇】函数
4.1 函数的定义 函数是指将一组语句的集合通过一个名字(函数名)封装起来,要想执行这个函数,只需调用其函数名即可 4.2 函数的创建 函数名的命名规则: 1.函数名必须以下划线或字母开头,可以包含任 ...
- WPF 开发备忘录
运营日: select t.* from (select ab.*, bs.station_cn_name, bd.device_name from audit_tvm_cas ...