2012-10-31 9 views
6

습득 조건 : https://code.google.com/apis/console/js에서 URL을 어떻게 단축합니까?

JS를 통해 원래의 URL로 get API를 goo.gl URL을 바꾸는 다양한 방법에 대한 문서가 많이가 있습니다에서 자신에게 urlshortener에 대한 API 키를 생성 예 : here, herehere - - 적어도 첫 번째 작품은 작동합니다. 내가 대신 { "longUrl": "https://codepen.io/" }를 전달에 URL을 작은 URL을 을 변환 할 insert API를 사용하려면 약간 어느 하나를 조정할 경우

하지만, 그것은 나누기. 만약 당신이 좋아하면 http://codepen.io/johan/full/EHbGy#YOUR-API-KEY-HERE에서 그것을 시도, 또는이 어딘가에 실행 오류와 함께

<script> 
var api_key = 'YOUR-API-KEY-HERE'; 

function makeRequest() { 
    var request = gapi.client.urlshortener.url.insert({ 
    'longUrl': 'https://codepen.io/' 
    }); 
    request.execute(function(response) { 
    alert(JSON.stringify(window.got = response)); 
    }); 
} 

function load() { 
    gapi.client.setApiKey(api_key); 
    gapi.client.load('urlshortener', 'v1', makeRequest); 
} 
</script> 
<script src="https://apis.google.com/js/client.js?onload=load"></script> 

... 그냥 응답을 :

{ "code": 400 
, "message": "Required" 
, "data": 
    [ { "domain": "global" 
    , "reason": "required" 
    , "message": "Required" 
    , "locationType": "parameter" 
    , "location": "resource.longUrl" 
    } 
    ] 
, "error": 
    { "code": 400 
    , "message": "Required" 
    , "data": 
    [ { "domain": "global" 
     , "reason": "required" 
     , "message": "Required" 
     , "locationType": "parameter" 
     , "location": "resource.longUrl" 
     } 
    ] 
    } 
} 

제안? (아니요, resource.longUrl 키가있는 객체에 url.insert 매개 변수를 변경하거나 래퍼 객체없이 URL 만 전달하면 더 이상 작동하지 않습니다.

답변

6

문서 또는 오류 메시지에서 너무 명확하지는 않지만, 하지만 귀하의 요청은 다음과 같이해야하며, 모두 잘 될 것입니다 :

var request = gapi.client.urlshortener.url.insert({ 
    'resource': {'longUrl': 'https://codepen.io/'} 
}); 
+0

감사합니다. 좋은 문서를 유지하는 것은 좋은 API를 만드는 것만 큼 어렵습니다. – ecmanaut

+0

@ecmanaut'URL Resource'의 예제 링크가 도움이되지 않았다는 것을 의미합니까? https://developers.google.com/url-shortener/v1/url/url#resource – doublesharp

+0

developers.google.com이 (사용자가 Google 웹 마스터 도구를 사용하여) 404 명의 사용자를 분류 할 수있는 기회를 제공합니다. . 나는 끊임없는 전임 QA의 위치라는 것을 알 수 있었다. – ecmanaut

1

나는 그것이 밝혀 때 내가 모든로드하는 대신 커피 스크립트의 다섯 줄을 수행 할 수 있습니다, 나는이에 대한 지저분한 클라이언트 라이브러리를 삭제할 것 같아요 jQuery를 이미 가지고 있기 때문에 그 cruft는 다음과 같습니다. http://codepen.io/johan/pen/puJyH

api = 'https://www.googleapis.com/urlshortener/v1/url' 
api += "?key=#{key}" if key = location.search.slice 1 

$.ajax 
    url: api 
    type: 'POST' 
    data: JSON.stringify(longUrl: url) 
    contentType: 'application/json' 
    success: (got) -> 
    alert "shortened url: #{got.id}" 
+0

참고 :이 [insert] (https://developers.google.com/url-shortener/v1/url/insert) api는 11 월 15 일 이전부터 정상적으로 작동했지만 이후 CORS OPTIONS 요청이 404 오류와 함께 실패했습니다. 실제 POST는 발생할 수 없습니다. [메일 링리스트] (https://groups.google.com/forum/?fromgroups=#!forum/google-url-shortener) 및 docs 사이트에서 버그 보고서를 제출했습니다. 귀하의 페이지를 대신하여 non-CORS rpc ajax 요청을 수행하는 숨겨진 www.googleapis.com iframe을 생성하기 위해 뒤로 구부리기 때문에 Google js 클라이언트는 여전히 작동합니다. 이것에 대해 – ecmanaut

+0

감사합니다. 그것은 정말로 나를 도왔다! –