Logo

C# 后台Http访问 raw from 键值对

photo

2020年09月08日

using RestSharp;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace Quotation.Common.Extensions
{


public class HttpRequstExtensions
{


/// <summary>
/// 参数
/// </summary>
/// <param name="url"></param>
/// <param name="data"></param>
/// <returns></returns>
public static string httpPostAsync(string url, List<KeyValuePair<string, string>> data)
{
        HttpClient client = new HttpClient();
        var form_data = new FormUrlEncodedContent(data);
        var reponse = client.PostAsync(url, form_data);
        if (reponse.IsCompleted)
        {
              var result = reponse.Result;
              var resdata = result.Content.ReadAsStringAsync();
              return resdata.ToString();
        }
        return "";
}


/// <summary>
/// 发送Get请求,获取内容
/// </summary>
/// <param name="url"></param>
/// <returns></returns>
public static string HttpGet(string url)
{
         HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
         request.Credentials = CredentialCache.DefaultCredentials;
         HttpWebResponse response = (HttpWebResponse)request.GetResponse();
         Stream receiveStream = response.GetResponseStream();
         StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8);
         string text = readStream.ReadToEnd();
         response.Close();
         readStream.Close();
         return text;
}


/// <summary>
/// Post请求
/// </summary>
/// <param name="url"></param>
/// <param name="pars"></param>
/// <returns></returns>
public static string HttpPost(string url, string pars, string contentType = "")
{
          byte[] bytes = Encoding.UTF8.GetBytes(pars);
          HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
          request.Method = "POST";
          request.ContentLength = bytes.Length;
          //request.ContentType = "text/xml";
          if (!string.IsNullOrEmpty(contentType))
                request.ContentType = contentType;
          request.Credentials = CredentialCache.DefaultCredentials;

          //Stream writer = request.GetRequestStream();
          //writer.Write(bytes, 0, bytes.Length);
          //writer.Close();

          HttpWebResponse response = (HttpWebResponse)request.GetResponse();
          Stream receiveStream = response.GetResponseStream();
          StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8);
          string text = readStream.ReadToEnd();
          response.Close();
          readStream.Close();
          return text;
}


/// <summary>
/// 1.1公用 from 键值对,固定参数
/// </summary>
/// <param name="url"></param>
/// <param name="promotionId"></param>
/// <param name="resultCode"></param>
/// <param name="resultDesc"></param>
/// <returns></returns>
public static string RestSharpPost(string url, string promotionId, int resultCode, string resultDesc)
{
           RestClient client = new RestClient(url);
           RestRequest request = new RestRequest(Method.POST);
           request.AddParameter("promotionId", promotionId);
           request.AddParameter("resultCode", resultCode);
           request.AddParameter("resultDesc", resultDesc);
           IRestResponse response = client.Execute(request);
           if (response.StatusCode == HttpStatusCode.OK)
           {
                  return response.Content;
           }
           else
           {
                  return response.ErrorException.StackTrace;
           }
}


/// <summary>
/// 1.2公用 from 键值对
/// </summary>
/// <param name="url"></param>
/// <param name="ht"></param>
/// <returns></returns>
public static string RestSharpPost(string url, Hashtable ht)
{
           RestClient client = new RestClient(url);
           RestRequest request = new RestRequest(Method.POST);
           if (ht != null && ht.Count > 0)
           {
                   foreach (DictionaryEntry de in ht)
                   {
                            request.AddParameter(de.Key.ToStr(), de.Value);
                   }
           }
           IRestResponse response = client.Execute(request);
           if (response.StatusCode == HttpStatusCode.OK)
           {
                    return response.Content;
           }
           else
           {
                    return response.ErrorException.StackTrace;
           }
}

/// <summary>
/// 1.3公用raw 推荐使用
/// </summary>
/// <param name="url"></param>
/// <param name="data">json 字符串</param>
/// <returns></returns>
public static string RestSharpPostRaw(string url, string data)
{
           RestClient client = new RestClient(url);
           RestRequest request = new RestRequest(Method.POST);
           if (!string.IsNullOrEmpty(act))
           {
                      request.AddHeader("content-type", "application/json");
                      request.AddParameter("application/json", data, ParameterType.RequestBody);
           }

           IRestResponse response = client.Execute(request);
           if (response.StatusCode == HttpStatusCode.OK)
           {
                      return response.Content;
           }
           else
           {
                      return response.ErrorException.StackTrace; //异常信息返回
           }
}

 

调用   Raw

string ret= "";
string url= "https://www.xxxx.com/index/update";

//对象参数

var data = new { shopId="你好1", grossProfit = "你好2", rebate = "你好3"};

try
{
          //第一种方法调用Raw
          ret = HttpRequstExtensions.RestSharpPostRaw(url, data.ToJson());

          //第二种方法调用Raw
          //ret = HttpRequstExtensions.HttpPost(url, data.ToJson(), "application/json");

}
catch
{

}

 

//json  反 json string字符串

public static string ToJson(this object obj)
{
           var json = string.Empty;
           try
           {
              var jSetting = new JsonSerializerSettings { ContractResolver = new NullToEmptyStringResolver(), DateFormatString = "yyyy-MM-dd HH:mm:ss" };
              json = JsonConvert.SerializeObject(obj, jSetting);
           }
           catch
           {
              return json;
           }
           return json;
}

 

/// <summary>
/// json转对象忽略大小写
/// </summary>
/// <typeparam name="T">对象类型</typeparam>
/// <param name="json"></param>
/// <returns></returns>
public static T ToObject<T>(this string json) where T : new()
{
           try
           {
                 if (string.IsNullOrEmpty(json))
                     return new T();
                 return JsonConvert.DeserializeObject<T>(json);
           }
           catch (Exception ex)
           {
                return new T();
           }
}

 

}}

 

橙子主题打折出售

其实我不卖,主要是这里是放广告的,所以就放了一个
毕竟主题都没做完,卖了也是坑.

购买它
所有附件
该文章没有附件.
本文为原创文章,请注意保留出处!

热门文章

Navicat Premium 12.0.22 安装与破解 一、安装  NavicatPremium12.0.22的下载链接:https://pan.ba...NavicatPremium12.0.22安装与破解 作者:Pastore Antonio
1515 浏览量
C# JArray与JObject 的使用 STEP1、usingNewtonsoft.Json.Linq;STEP2、如何获取json里的...C#JArray与JObject的使用 作者:Pastore Antonio
1465 浏览量
解决mysql的配置ONLY_FULL_GROUP_BY引起的错误 由于自己的本地网站环境使用了mysql8.0的版本,在测试一个groupby的sql查...解决mysql的配置ONLY_FULL_GROUP_BY引起的错误 作者:Pastore Antonio
1448 浏览量
Windows server 2016 英文服务器安装中文语言包教程 1、下载windowsserver2016语言包下载地址:https://pan.baidu....Windowsserver2016英文服务器安装中文语言包教程 作者:Pastore Antonio
1407 浏览量
assembly(全局程序集缓存)中dll的导入和导出 本文主要讲一下关于assembly中的dll是怎么导入和导出的。浏览量:1,468 作者:Pastore Antonio
1403 浏览量