使用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

若有前辈能够指点一下感激涕零。测试

相关文章
相关标签/搜索