Skip to content

Instantly share code, notes, and snippets.

@zeraf29
Created October 15, 2017 15:27
Show Gist options
  • Save zeraf29/6635f21e961e5483296958daec66a58a to your computer and use it in GitHub Desktop.
Save zeraf29/6635f21e961e5483296958daec66a58a to your computer and use it in GitHub Desktop.
구글 short url api 를 이용한 단축 url 생성 매서드(C#)
public static string SimpleUrl(string orgUrl)
{
string shortUrl = "";
string key = "google key"; //Google 단축키 Key URL
var request = (HttpWebRequest)WebRequest.Create("https://www.googleapis.com/urlshortener/v1/url?key=" + key);
//google simple url api 로 key 값 전달
request.ContentType = "application/json";
request.Method = "POST";
request.ContentType = "application/json";
using (var streamWriter = new StreamWriter(request.GetRequestStream())) //stream 생성
{
string json = "{\"longUrl\":\"" + orgUrl + "\"}"; //단축하려는 long url 값을 json 값으로 생성
streamWriter.Write(json); //생성한 json 값 stream으로 전달
streamWriter.Close();
}
var httpResponse = (HttpWebResponse)request.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream(), Encoding.UTF8))
{
JObject json = JObject.Parse(streamReader.ReadToEnd());//JSon 형식으로 전달받은 Stream 값을 Json으로 변환
shortUrl = json["id"].ToString(); //전달 받은 값중 id값(축약된 url 값)을 선택하여 string 변환
streamReader.Close();
httpResponse.Close();
}
return shortUrl;
}
@zeraf29
Copy link
Author

zeraf29 commented Oct 15, 2017

내부 api 라이브러리를 쓰지 않고 url 상으로 전달 받아 축약하는 방법.
전달 값에 따라 축약 주소를 다시 long url 로 변환 가능

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment