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

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();
           }
}

 

}}

 

posted @ 2017-05-10 17:25  cclon  阅读(5266)  评论(0编辑  收藏  举报