net mvc get post 第三方API数据

http://blog.csdn.net/kingcruel/article/details/44036871

客户非要那个阿凡达数据 真特么坑。没有调用示例不说,官方demo也有错误。。。

这块完成了,可以把代码贴出来。。。

controller 两种方式,因为阿凡达数据 post 不能用,客服说要换成get试试。好吧,get就get,能用就行。但是翻译功能 确实不能用,因为官方的demo就有问题。

try
            {

                #region DoGet
                Dictionary<String, String> dicList = new Dictionary<String, String>();
                dicList.Add("key", translate.key);
                dicList.Add("query", translate.query);
                dicList.Add("from", translate.from);
                dicList.Add("to", translate.to);
                dicList.Add("format", translate.format);


                String parameter = buildQueryStr(dicList);

                string resultStr = this.DoGet(translate.url + "?" + parameter);

                #endregion

                #region DoPost



                //Dictionary<String, String> dicList = new Dictionary<String, String>();


                //dicList.Add("key", translate.key);
                //dicList.Add("query", translate.query);
                //dicList.Add("from", translate.from);
                //dicList.Add("to", translate.to);
                //dicList.Add("format", translate.format);

                //string postStr = StringProc.buildQueryStr(dicList);

                //string resultStr = this.DoPost(translate.url, postStr);

                #endregion

                #region
                //string RequestURL = "http://api.avatardata.cn/Dictionary/Translate?key=4aa265d8ace8432c8ea0d931f69ac017&query=我是中国人&from=cn&to=en";
                //string resultStr = null;
                //HttpWebResponse response = null;
                //HttpWebRequest request = WebRequest.Create(RequestURL) as HttpWebRequest;
                //request.Accept = "application/json";
                //request.ContentType = "application/json; charset=utf-8";
                //request.Method = "GET";
                //response = (HttpWebResponse)request.GetResponse();
                resultStr = ReadHttpResponse(response);


                //var responseStream = response.GetResponseStream();
                //if (responseStream != null && (response.StatusCode == HttpStatusCode.OK && responseStream.CanRead))
                //{
                //    resultStr = new StreamReader(response.GetResponseStream()).ReadToEnd();
                //}
                //response.Close();
                #endregion
                return Json(resultStr);
            }
        #region 通用方法
        public static String buildQueryStr(Dictionary<String, String> dicList)
        {
            String postStr = "";

            foreach (var item in dicList)
            {
                postStr += item.Key + "=" + HttpUtility.UrlEncode(item.Value, Encoding.UTF8) + "&";
            }
            postStr = postStr.Substring(0, postStr.LastIndexOf('&'));
            return postStr;
        }

        /// <summary>  
        /// GET Method  
        /// </summary>  
        /// <param name="portraitUri">url地址</param>  
        /// <returns></returns>  
        private String DoGet(string portraitUri)
        {
            MyHttpClient client = new MyHttpClient(portraitUri);
            return client.ExecuteGet();
        }

        /// <summary>  
        /// POST Method  
        /// </summary>  
        /// <param name="portraitUri">url地址</param>  
        /// <param name="postStr">请求参数</param>  
        /// <returns></returns>  
        private String DoPost(string portraitUri, string postStr)
        {
            MyHttpClient client = new MyHttpClient(portraitUri, postStr);
            return client.ExecutePost();
        }


        #endregion

下面是 MyHttpClient.cs

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;

namespace XXX.Extension
{

    /// <summary>
    /// http://blog.csdn.net/kingcruel/article/details/44036871
    /// </summary>
    public class MyHttpClient
    {
        public string methodUrl = string.Empty;
        public string postStr = null;

        public MyHttpClient(String methodUrl)
        {
            this.methodUrl = methodUrl;
        }

        public MyHttpClient(String methodUrl, String postStr)
        {
            ///this.methodUrl = ConfigurationManager.AppSettings["ApiFrontEnd"];///http://192.168.1.6:8098/Signin/LoginApi  
            ///this.postStr = postStr;  

            this.methodUrl = methodUrl;
            this.postStr = postStr;
        }

        /// <summary>  
        /// GET Method  
        /// </summary>  
        /// <returns></returns>  
        public String ExecuteGet()
        {
            HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(this.methodUrl);
            myRequest.Method = "GET";

            myRequest.Accept = "application/json";
            myRequest.ContentType = "application/json; charset=utf-8";

            HttpWebResponse myResponse = null;
            try
            {
                myResponse = (HttpWebResponse)myRequest.GetResponse();
                StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
                string content = reader.ReadToEnd();
                return content;
            }
            //异常请求  
            catch (WebException e)
            {
                myResponse = (HttpWebResponse)e.Response;
                using (Stream errData = myResponse.GetResponseStream())
                {
                    using (StreamReader reader = new StreamReader(errData))
                    {
                        string text = reader.ReadToEnd();

                        return text;
                    }
                }
            }
        }

        /// <summary>  
        /// POST Method  
        /// </summary>  
        /// <returns></returns>  
        public string ExecutePost()
        {
            string content = string.Empty;

            //Random rd = new Random();  
            //int rd_i = rd.Next();  
            //String nonce = Convert.ToString(rd_i);
            //String timestamp = Convert.ToString(StringProc.ConvertDateTimeInt(DateTime.Now));  
            //String signature = GetHashCode(this.appSecret + nonce + timestamp);  

            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(this.methodUrl);
                request.Method = "POST";

                request.Accept = "application/json";
                request.ContentType = "application/json; charset=utf-8";

                //request.ContentType = "application/x-www-form-urlencoded";


                //request.Headers.Add("Nonce", nonce);  
                //request.Headers.Add("Timestamp", Convert.ToString(StringProc.ConvertDateTimeInt(DateTime.Now)));  
                //request.Headers.Add("Signature", signature);  
                request.ReadWriteTimeout = 30 * 1000;

                byte[] data = Encoding.UTF8.GetBytes(postStr);
                request.ContentLength = data.Length;

                Stream myRequestStream = request.GetRequestStream();

                myRequestStream.Write(data, 0, data.Length);
                myRequestStream.Close();

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                StreamReader myStreamReader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                content = myStreamReader.ReadToEnd();
                myStreamReader.Close();
            }
            catch (Exception ex)
            {
                content = ex.Message;
            }
            return content;
        }
    }

    public class StringProc
    {
        public static String buildQueryStr(Dictionary<String, String> dicList)
        {
            String postStr = "";

            foreach (var item in dicList)
            {
                postStr += item.Key + "=" + HttpUtility.UrlEncode(item.Value, Encoding.UTF8) + "&";
            }
            postStr = postStr.Substring(0, postStr.LastIndexOf('&'));
            return postStr;
        }

        public static int ConvertDateTimeInt(System.DateTime time)
        {
            System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
            return (int)(time - startTime).TotalSeconds;
        }

    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值