[javascript]Google URL Shortener API
Googleの短縮URL「goo.gl」がAPIの提供を開始http://blog.fkoji.com/2011/01110730.html
したらしいので早速いじってみました。
あらかじめ下記サイトでAPIキーを取得しておきましょう。
URL Shortener APIのActivateボタンを押して表示されたURLのkeyの値がAPIキーです。
http://code.google.com/apis/console/
APIキーを取得したらあとはごりごり書くだけ。
PHP
< ?php $apikey='APIキー'; $url="https://www.googleapis.com/urlshortener/v1/url" . '?key=' . $apikey; $longurl=$_GET["longUrl"]; $shorturl=$_GET["shortUrl"]; if($longurl){ $request='{"longUrl": "' . $longurl . '"}'; $headers = array('Content-Type:application/json'); $conn = curl_init(); curl_setopt($conn, CURLOPT_URL, $url); curl_setopt($conn, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($conn, CURLOPT_POSTFIELDS, $request); curl_setopt($conn, CURLOPT_RETURNTRANSFER, 1); curl_setopt($conn, CURLOPT_POST, true); curl_setopt($conn, CURLOPT_HEADER, false); curl_setopt($conn, CURLOPT_HTTPHEADER, $headers); }elseif($shorturl){ $url .= '&shortUrl=' . $shorturl; $conn = curl_init(); curl_setopt($conn, CURLOPT_URL, $url); curl_setopt($conn, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($conn, CURLOPT_RETURNTRANSFER, 1); curl_setopt($conn, CURLOPT_HEADER, false); }else{ echo "error"; exit; } $ret=curl_exec($conn); echo $ret; curl_close($conn); exit; ?>
Javascript
//短縮するとき var m={'longUrl':対象URL}; ajax_get('action.php', m, when_get_shorturl); //元に戻すとき var m={'shortUrl':対象URL}; ajax_get('action.php', m, when_get_longurl); function when_get_shorturl(data){ var m=eval("("+data+")"); } function when_get_longurl(data){ var m=eval("("+data+")"); } function ajax_get(cgi_path, param, finish_func){ var httpObj = createHttpRequest(); if(!httpObj)return; var str=get_post_param(param); if(str!="")cgi_path+=('?'+str); httpObj.open("GET",cgi_path, true); httpObj.onreadystatechange=function(){ if(httpObj.readyState == 4 && httpObj.status == 200){ var data=httpObj.responseText; finish_func(data); } } httpObj.setRequestHeader('Content-Type','application/x-www-form-urlencoded; charset=UTF-8'); httpObj.send(); } function get_post_param(param){ if(!param)return ""; var a; var str=""; var m; var b; for(b in param){ str+=b+"="+encodeURIComponent(param[b]); str+="&"; } str=str.substring(0,str.length-1); return str; } function createHttpRequest(){ var x=null; if (window.XMLHttpRequest)return new XMLHttpRequest(); try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch(e) { try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch(e) { x = null; } } return x; }
参考にしたサイト
Google Code – Google URL Shortener API
http://code.google.com/intl/ja/apis/urlshortener/