繁体   English   中英

使用XMLHttpRequest通过Google的Shortener API缩短网址

[英]Using XMLHttpRequest to shorten a url via Google's Shortener api

我已经尝试通过jQuery / ajax来执行此操作,但是它没有用,所以我认为我会退回到普通的XMLHttpRequest。 不幸的是,它仍然无法正常工作(同样的问题)。

这是Google POST请求的文档。 这是我的代码:

var xmlHttp = new XMLHttpRequest();

xmlHttp.open("POST", "https://www.googleapis.com/urlshortener/v1/url", true);
xmlHttp.setRequestHeader("Content-Type", "application/json");

var url = "longUrl=" + encodeURIComponent("http://www.google.com/");
console.log(url);

xmlHttp.send(url);

“ url”以以下形式发送到控制台:longUrl = http%3A%2F%2Fwww.google.com%2F

响应为:

{
 "error": {
  "errors": [
   {
    "domain": "global",
    "reason": "parseError",
    "message": "Parse Error"
   }
  ],
  "code": 400,
  "message": "Parse Error"
 }
}

有人看到我在做什么错吗?

提前致谢!

编辑:为@Greg添加-以便您可以看到我在使用jQuery 遵循Google的规范-导致完全相同的错误。

$.ajax({
    type: "POST",
    contentType: "application/json; charset=utf-8",
    data: { "longUrl": "http://www.google.com/" },
    url: "https://www.googleapis.com/urlshortener/v1/url",
    success: function(data) {
        //do something with the shortened url json data
        //console.log(data);
    }
});

这是解决方案(@Greg的评论向我指出了正确的方向)。

var xmlHttp = new XMLHttpRequest();

xmlHttp.open("POST", "https://www.googleapis.com/urlshortener/v1/url", true);
xmlHttp.setRequestHeader("Content-Type", "application/json; charset=utf-8");

var req = new Object();
req.longUrl = "http://www.google.com/";

var jsonStr = JSON.stringify(req);

xmlHttp.send(jsonStr);

您没有遵循Google提供的规范。 您应该像这样发送JSON对象:

{"longUrl": "http://www.google.com/"}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM