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>
/// 反序列化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>
/// <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;
}
}
}

C# HttpClient请求的更多相关文章

  1. httpclient请求方法

    /** * httpclient请求方法 * @param url 请求地址 * @param paramMap 请求参数 * @param ent 编码格式 gbk.utf-8 * @return ...

  2. HttpClient请求服务器代码优化版

    HttpClient请求服务器代码优化版 首先,我在前面的两篇博文中介绍了在 Android中,除了使用java.net包下HttpUrlConnection的API访问HTTP服务之外,我们还可以换 ...

  3. 通过HttpClient请求webService

    通过HttpClient请求webService 由于服务端是用webService开发的,android要调用webService服务获取数据,这里采用的是通过HttpClient发送post请求, ...

  4. C# HttpClient 请求认证、数据传输笔记

    目录 一,授权认证 二,请求类型 三,数据传输 C# HttpClient 请求认证.数据传输笔记 一,授权认证 客户端请求服务器时,需要通过授权认证许可,方能获取服务器资源,目前比较常见的认证方式有 ...

  5. SpringMVC获取HttpClient 请求的数据

    package com.nnk.upstream.controller;import org.springframework.util.StreamUtils;import javax.servlet ...

  6. .NetCore简单封装基于IHttpClientFactory的HttpClient请求

    IHttpClientFactory是什么?为什么出现了IHttpClientFactory 一.IHttpClientFactory是什么? IHttpClientFactory是.netcore2 ...

  7. .NET Core HttpClient请求异常详细情况分析

    前言 最近项目上每天间断性捕获到HttpClient请求异常,感觉有点奇怪,于是乎观察了两三天,通过日志以及对接方沟通确认等等,查看对应版本源码,尝试添加部分配置发布后,观察十几小时暂无异常情况出现, ...

  8. Httpclient请求数据(post)

    public static String loginCheck_POST_HttpClient(String name,String pass,String url){ String result = ...

  9. HttpClient请求

    HttpClient HttpClient 是 Apache Jakarta Common 下的子项目,用来提供高效的.最新的.功能丰富的支持 HTTP 协议的客户端编程工具包, 并且它支持 HTTP ...

  10. HttpClient请求返回JSON、图片

    /** * Created by RongGuang on 2015/9/19. */ public class RongHttp { /** * Http Post请求 * @param url * ...

随机推荐

  1. MyBean-关于单实例插件

    单实例插件可以通过两个途径实现 第一个在注册时注册成单实例 beanFactory.RegisterBean(pvPluginID: String; pvClass: TClass;     pvSi ...

  2. mac下增加eclipse内存

    在mac上找不到eclipse.ini文件编辑内存限制,在eclipse安装目录右击eclipse程序,选“显示包内容”,eclipse.ini就在 Content/MacOS下.

  3. LeetCode: Palindrome Partitioning 解题报告

    Given a string s, partition s such that every substring of the partition is a palindrome. Return all ...

  4. django —— Celery实现异步和定时任务

    1. 环境 python==2.7 djang==1.11.2 # 1.8, 1.9, 1.10应该都没问题 celery-with-redis==3.0 # 需要用到redis作为中间人服务(Bro ...

  5. Linux: grep多个关键字“与”和“或”

    1.或操作 grep -E '123|abc' filename // 找出文件(filename)中包含123或者包含abc的行 egrep '123|abc' filename // 用egrep ...

  6. 【Java】HashTable和HashMap区别

    ①继承不同 public class Hashtable extends Dictionary implements Map public class HashMap extends Abstract ...

  7. Oracle Database 11g Release 2 Standard Edition and Enterprise Edition Software Downloads

    Oracle Database 11g Release 2 Standard Edition and Enterprise Edition Software DownloadsOracle 数据库 1 ...

  8. php多进程编程相关资料(以备参考)

    进程与线程的区别 要了解二者的区别与联系,首先得对进程与线程有一个宏观上的了解. 进程,是并发执行的程序在执行过程中分配和管理资源的基本单位,是一个动态概念,竟争计算机系统资源的基本单位.每一个进程都 ...

  9. 记录 am335x 因为 pinmux 配置不对导致 不断的原因

    其实很简单,是因为 中断不仅仅需要 gpio 的 input 属性, 还需要 pull_up 的数据 {"gpmc_ad11.gpio0_27", OMAP_MUX_MODE7 | ...

  10. Virtools元素、类和面向对象设计

    无意中发现了在某个不存在的网站( https://sites.google.com )上,还存有09年写的一些半成品教材,下面这篇文章就是其中一部分. 概述 Virtools将元素(Element)组 ...