需要调用一个第三方接口,传参返回数据
本来是很简单的一个需求,搞了一天没整好
首先在POSTMAN中测试没有问题,但是使用jquery ajax在前台就会涉及到跨域
虽然设置了 无论怎么写都会报错
Cross-Origin Read Blocking (CORB) blocked cross-origin response https://xxxxxxxxxxxxxxx/xxxxx?
callback=jQuery203024259184329991657_1533652268651&appkey=xxxxxx×tamp=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+"×tamp=" + 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; }
虽然把问题解决了,但是怎么在客户端调用,还是没弄明白,自己理解的也不一定对。
如有前辈可以指点一下感激不尽。