[Windows Phone] App 範例 [PTT 短網址]

  • 3195
  • 0
  • 2013-11-01

在 iT邦幫忙鐵人賽的最後一天不知道要寫什麼,看到市集上有人寫 PTT 短網址,想說不難,就寫一下當範例。

 

前言

在 iT邦幫忙鐵人賽的最後一天不知道要寫什麼,看到市集上有人寫 PTT 短網址,想說不難,就寫一下當範例。

 

實作

以設計模式開啟 MainPage.xaml,加入兩個 TextBox 和一個 Button,第一個 TextBox 讓使用者輸入網址,當按下 Button 時,將產生的短網址結果顯示在第二個 TextBox 中,並且儲存到剪貼簿。

 


<StackPanel>
    <TextBox x:Name="tbUri" Text="http://www.dotblogs.com.tw" />
    <Button x:Name="btnGeneration" Content="產生 PPT 短網址" Click="btnGeneration_Click" />
    <TextBox x:Name="tbPTTCoder" />
</StackPanel>

 

image

 

切換到程式碼,透過 HttpWebRequest 和 HttpWebResponse 來發送需求與回傳結果,PTT 縮網址的方式請參考此網址說明 :

http://ppt.cc/x/%E7%A8%8B%E5%BC%8F%E9%96%8B%E7%99%BC%E5%8F%83%E8%80%83

 

image

 

完整程式碼


using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using PTTcoderApp.Resources;
using System.IO;

namespace PTTcoderApp
{
    public partial class MainPage : PhoneApplicationPage
    {
        // 建構函式
        public MainPage()
        {
            InitializeComponent();
        }

        private void btnGeneration_Click(object sender, RoutedEventArgs e)
        {
            HttpWebRequest request =
                (HttpWebRequest)WebRequest.Create(string.Format(@"http://ppt.cc/pttcoder.php?url={0}", tbUri.Text));
            request.BeginGetResponse(new AsyncCallback(GetHttpDocumentCallback), request);
        }

        private void GetHttpDocumentCallback(IAsyncResult res)
        {
            HttpWebRequest request = (HttpWebRequest)res.AsyncState;
            HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(res);
            string strPTTCoder = string.Empty;
            using (var reader = new StreamReader(response.GetResponseStream()))
            {
                strPTTCoder = string.Format(@"ppt.cc/{0}", reader.ReadToEnd());
            }

            Deployment.Current.Dispatcher.BeginInvoke(new Action(() =>
            {
                // 將結果放到剪貼簿
                System.Windows.Clipboard.SetText(strPTTCoder);
                // 將結果顯示在 tbPTTCoder
                tbPTTCoder.Text = strPTTCoder;
            }));
        }
    }
}

 

執行結果,當輸入 http://www.dotblogs.com.tw,按下按鈕後,產生 PTT 短網址。

SNAGHTML17228b82

 

在你想要貼上短網址的地方,例如 IE,可直接貼上短網址,確認後導向原始網址。

SNAGHTML17259d85SNAGHTML1725b717SNAGHTML1725d02d

 

範例下載

PTTcoderApp.zip