使用WebClient調用第三方接口


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

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

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

雖然設置了 無論怎么寫都會報錯

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,但是改了也沒有用。

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

無奈只好在后台實現

下面是我的代碼

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

雖然把問題解決了,但是怎么在客戶端調用,還是沒弄明白,自己理解的也不一定對。

如有前輩可以指點一下感激不盡。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM