使用WebClient調用第三方接口

須要調用一個第三方接口,傳參返回數據jquery

原本是很簡單的一個需求,搞了一天沒整好ajax

首先在POSTMAN中測試沒有問題,可是使用jquery ajax在前臺就會涉及到跨域chrome

雖然設置了 不管怎麼寫都會報錯json

Cross-Origin Read Blocking (CORB) blocked cross-origin response https://xxxxxxxxxxxxxxx/xxxxx?
callback=jQuery203024259184329991657_1533652268651&appkey=xxxxxx&timestamp=1533651720
&auth=xxxxxxxxxxxxxxxxx&image_url=http%3A%2F%2Fpic18.nipic.com%2F20120204%2F9114602_104351504000_2.jpg
&_=1533652268652 with MIME type application/json. See https://www.chromestatus.com/feature/5629709824032768 for more details.

上網查了一下好像是要設置content-type,可是改了也沒有用。api

又查了資料好像是沒有跨域權限,須要服務端設置Access-Control-Allow-Headers才能夠,可是我是調用方無法修改服務端配置跨域

無奈只好在後臺實現app

下面是個人代碼ide

 public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "text/plain";
        string appkey = "myappkey";
        string appsecret ="myappsecret";
        string timestamp = GetTimestamp().ToString();
        string image_url = "http://pic18.nipic.com/20120204/9114602_104351504000_2.jpg";
        string auth = GetMD5(appkey + "+" + timestamp + "+" + appsecret);
        string postData = "appkey="+appkey+"&timestamp=" + timestamp + "&auth=" + auth.ToLower() + "&image_url=" + image_url;
        byte[] bytes = Encoding.UTF8.GetBytes(postData);
        WebClient wc = new WebClient();
        wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
        wc.Headers.Add("ContentLength", postData.Length.ToString());
        Encoding enc = Encoding.GetEncoding("UTF-8");
        byte[] responseData = wc.UploadData("apiurl", "POST", bytes);
        string response = enc.GetString(responseData);
        context.Response.Write(response);
    }
    public string GetMD5(string myString)
    {
        byte[] result = Encoding.Default.GetBytes(myString);
        MD5 md5 = new MD5CryptoServiceProvider();
        byte[] output = md5.ComputeHash(result);
        return BitConverter.ToString(output).Replace("-", "");
    }

    public long GetTimestamp()
    {
        TimeSpan ts = DateTime.Now.ToUniversalTime() - new DateTime(1970, 1, 1);
        return (long)ts.TotalSeconds;
    }

雖然把問題解決了,可是怎麼在客戶端調用,仍是沒弄明白,本身理解的也不必定對。post

若有前輩能夠指點一下感激涕零。測試

相關文章
相關標籤/搜索