はてブをプログラムから追加する

投稿日 : 2008年7月27日 22:31

 はてなはあまり利用してないのだけど(人気エントリは昼休みに見てる)、ヘルプをさまよっていたら、はてなブックマークAtomAPI というのがあったのでVB.NETで実装してみたよ! 2005年からあったのかー。

 まず、つまづいた点から。ブックマークを追加する際にPOST投稿する必要があるのだけど、HttpWebRequestクラスを使って投稿した場合、サーバーから 417 Expectation Failed というエラーが返ってきていた。期待されるものがおかしいのか?? と思ってリクエスト内容がおかしいのかなーと調べてたけど、このエラーコードは、Expect リクエストヘッダフィールドに関するものらしい。.NET で通常 POSTするとこの Expect リクエストヘッダフィールドに「100 (Continue) ステータス」が指定されるようだ。これを指定するとPOSTデータを受け取る前に、サーバが受付拒否ができ、トラフィックを有効に利用できる感じだ。はてなサーバーはこのExpect リクエストを理解できねーとエラーを返してたのですな。

 .NETのコードで、どうやって解決するかというと、検索したらありました。

ServicePointManager.Expect100Continue = False

Sharedなプロパティです。これで一律 Expect を使用しない送信方法になるっぽい。Sharedなので使い方が微妙。作ったコードでは処理前に元の値を覚えておいて、処理後に元の値に戻しているけどマルチスレッドで破綻 オワタ。

 さて認証は、WSSE認証というものを使うらしい。仕様書のリンクはきれてるし詳細がよくわからないのだけど、とりあえず動いたのでOKでしょう。クライアントソフトはユーザのパスワードを記憶しておかないといけないので、少しめんどいですね。

 というわけで、説明もほどほどに(してないけど)コードはこちら。

Public Class HatenaBookmarkApi

    Private Shared _servicePostUri As String = "http://b.hatena.ne.jp/atom/post"

    Private Shared Function createWsseHeaderValue(ByVal username As String, ByVal password As String) As String

        Dim sha1 = New System.Security.Cryptography.SHA1CryptoServiceProvider
        Dim created = Now.ToString("s")
        Dim nonce = Guid.NewGuid.ToString
        Dim passwordDigest = Convert.ToBase64String( _
            sha1.ComputeHash(System.Text.Encoding.ASCII.GetBytes(nonce & created & password)))

        Return String.Format("UsernameToken Username=""{0}"", PasswordDigest=""{1}"", Nonce=""{2}"", Created=""{3}""", _
                             username, passwordDigest, Convert.ToBase64String(System.Text.Encoding.ASCII.GetBytes(nonce)), created)

    End Function

    Public Shared Function PostUri(ByVal username As String, ByVal password As String, ByVal uri As String, ByVal comment As String) As WebExceptionStatus

        Dim except100Continue = ServicePointManager.Expect100Continue
        ServicePointManager.Expect100Continue = False

        Dim request = CType(WebRequest.Create(_servicePostUri), HttpWebRequest)
        request.Method = "POST"

        request.Headers.Add("Authorization", "WSSE profile=""UsernameToken""")
        request.Headers.Add("X-WSSE", createWsseHeaderValue(username, password))
        request.Accept = "application/x.atom+xml, application/xml, text/xml, */*"
        request.ContentType = "application/x.atom+xml"

        Dim entry = <entry xmlns="http://purl.org/atom/ns#">
                        <title>dummy</title>
                        <link rel="related" type="text/html" href=<%= uri %>/>
                        <summary type="text/plain"><%= comment %></summary>
                    </entry>

        ' こっちでもまったく問題なし
        'Dim entry = "<entry xmlns=""http://purl.org/atom/ns#""><title>dummy</title><link rel=""related"" type=""text/html"" href=""" & uri & """ /><summary type=""text/plain"">" & comment & "</summary></entry>"


        Dim buf = System.Text.Encoding.UTF8.GetBytes(entry.ToString)
        request.ContentLength = buf.Length

        Try
            Dim stream = request.GetRequestStream
            stream.Write(buf, 0, buf.Length)
            stream.Close()

            request.GetResponse.Close()
            Return WebExceptionStatus.Success

        Catch ex As WebException
            Return ex.Status
        Finally
            ServicePointManager.Expect100Continue = except100Continue
        End Try

    End Function
End Class

 使い方はこちら。戻り値が、WebExceptionStatusなんだよねー。そういう使い方普通するんだろうか。でもBooleanはどうかと思う。

HatenaBookmarkApi.PostUri(username, password, "http://yahoo.co.jp", "[tag1][tag2][tag3]")

 

参考になったサイト

 作ってから知ったのだけど、こちらのサイトが参考になりそうですね。

 もっと調べて(検索して)から作れば良かった。というか、これ作るつもりではてなのヘルプをさまよってなかったからなぁ。

フィードバック

# はてダとWindows Live Writer

2008/08/30 1:04 by katamari.wankuma.com
はてダとWindows Live Writer

# re: はてブをプログラムから追加する

2008/12/03 13:48 by kk
上記のソースを参考に、VBではてブに登録するプログラムを作成したのですが、先日リニューアルしたはてブでは、"request.GetResponse.Close() " のレスポンスを閉じる部分でHTTPの403エラーが返ってきてしまうようになってしまいました。

サーバからこの部分でアクセス拒否されているようですが、色々試してみましたがやはり403エラーが返ってしまいます。。


何か考えられる要因はありますでしょうか。

# re: はてブをプログラムから追加する

2008/12/03 20:48 by JZ5
コメントありがとうございます。
確認してみたところ、リニューアルされて今までのAPIが使用できない状態みたいですね。そのうち修正されるかもしれません……。

#  ??????????????????????????? - SharpLab.

2008/12/16 10:52 by Pingback/TrackBack
??????????????????????????? - SharpLab.

# laPAfzBcEw

2014/08/06 23:15 by http://crorkz.com/
iMcuLW Muchos Gracias for your article post.Thanks Again.

# GROUdrjixJIFsKwv

2014/09/03 9:52 by http://ecommerce-investments.com/boat-safety-acces
I savor, lead to I discovered just what I was having a look for. You have ended my four day long hunt! God Bless you man. Have a great day. Bye

# obrQyQuqZZTmiZKVZYp

2014/09/09 10:41 by http://vender-na-internet.com/
I was suggested this web site via my cousin. I am no longer certain whether this submit is written by him as nobody else realize such designated about my problem. You are incredible! Thanks!

# jdRVXPRkOFLhg

2014/09/09 15:15 by http://musiccomposingsoftware.org.
Great website. A lot of helpful information here. I am sending it to some friends ans additionally sharing in delicious. And certainly, thanks to your sweat!

# donde puedo conseguir en bogota

2018/01/07 4:59 by farmacia-en-linea.life
Comprar argentina http://farmacia-en-linea.life/belozok.html online Peru.

# For sale in las vegas

2018/01/08 6:43 by Buy real online usa
where can i buy over the counter in uk http://ecolejudotresses.com/index.php/component/k2/itemlist/user/102685 how much does cost over the counter.

# Average price of uk

2018/01/08 7:45 by Order generic from canada
price of in australia http://www.megagroup.co.za/?option=com_k2&view=itemlist&task=user&id=156349 how much does cost with insurance.

# Buying online safeguard

2018/01/08 18:29 by obtaining online
tablet buy online http://webuycadiis.cadii-shop.co.za/user/profile/5643 order online without doctors.

# Can you order online

2018/01/08 22:27 by retail price usa
buying without insurance https://eomi.ru/board/user/profile/8267 cheapest online.

# Tablet online purchase

2018/01/09 0:09 by overnight delivery canada
cost of in usa https://www.hub.careers/blogs/entry/What-Google-Can-Teach-You-About-Lowest-Price is buying online safe.

# For sale online usa

2018/01/09 5:41 by where to order generic
non prescription uk https://anenii-noi.md/?option=com_k2&view=itemlist&task=user&id=307908 order.

# Medicament maroc

2018/01/10 1:13 by medicamentsonline.life
Acheter en algerie http://medicamentsonline.life/ozurdex.html prix le moins cher.

# rendel&amp;#233;s &amp;#225;ra

2018/01/11 23:23 by gyogyszertarhu.life
Elad budapest, http://gyogyszertarhu.life/fertomid.html - Rendelés magyarországon.

# receptfritt sverige

2018/01/12 4:12 by Apotekvarer Pa Nettet
alternativ till europe, http://apotekvarerpanettet.life/serevent.html , köpa i USA priser.

# receptfritt tabletter

2018/01/12 8:14 by apotekvarer pa nettet
billig göteborg, http://apotekvarerpanettet.life/pamelor.html , receptfritt USA.

# apotek Sverige Oslo

2018/01/12 9:56 by apoteknettbutikknorge life
billig online Danmark, http://apoteknettbutikknorge.life/sinequan.html , Gunstige bergen.

# kostprijs

2018/01/12 11:41 by ONLINE APOTHEKER ZONDER RECEPT
Kopen in duitsland te koop, http://onlineapothekerzonderrecept.life/ventolin.html , nederland kopen frankrijk.

# goedkoop kopen in nederland

2018/01/12 17:11 by ONLINE APOTHEKER ZONDER RECEPT
Kopen belgie online, http://online-apotheker-zonder-recept.life/tricor.html , nederland kopen prijs.

# bestille online Danmark

2018/01/12 18:21 by apotek nettbutikk norge life
uten resept i Norge pris, http://apotek-nettbutikk-norge.life/sinemet.html , Hvor kjøpe online.

# prijs frankrijk niet

2018/01/13 5:58 by Apotheker Online Nederland
Kopen in duitsland frankrijk, http://online-apotheker-nederland.life/furosemide.html , kopen spanje kopen.

# elad&amp;#243;

2018/01/13 10:35 by Gyogyszertar Hungaria Online
ára receptek, http://online-gyogyszertar.life/purim.html - természetes tabletta.

# k&amp;#246;pa online danmark

2018/01/13 11:45 by APOTEKVARER PA NETT
köp billigt, http://apotekvarerpanettet.life/serevent.html , kostnad priser.

# pillen kopen amsterdam

2018/01/13 11:48 by Online Apotheek Zonder Recept
Bestellen via internet kopen, http://onlineapotheekzonderrecept.life/paroxetine.html , kopen online amsterdam.

# rendel&amp;#233;s n&amp;#233;lk&amp;#252;l recept

2018/01/13 15:53 by Gyogyszertar Online Hungaria
online vásárlás, http://gyogyszertar-online.life/nitrofurantoin.html - természetes.

# generic ds online

2018/01/13 19:29 by Apotek Pa Natet Sverige
pris apotek göteborg, http://apotekvarerpanettet.life/tenormin.html , amsterdam Sverige.

# beste sted &amp;#229; kj&amp;#248;pe pris

2018/01/14 3:42 by apoteknorgeonline
uten resept jeg, http://apoteknorgeonline.life/cytoxan.html , uten resept i Sverige.

# k&amp;#246;lts&amp;#233;g &amp;#225;rfolyamok

2018/01/14 8:11 by Gyogyszertarban Online Hungaria
alacsony árfolyamok, http://gyogyszertarban-online.life/nizoral.html - on-line árfolyamok.

# kapslar billigt

2018/01/14 10:25 by Sverige Apotek Pa Natet
alternativ till priser, http://apotekvarerpanettet.life/pamelor.html , generisk receptfritt.

# kostnad receptfritt

2018/01/14 16:38 by Apotek Pa Natet Sverige
malmö billigt, http://apotekvarerpanettet.life/noroxin.html , till salu priser.

# Cost without insurance

2018/01/16 1:36 by pills purchase online
buy australian http://www.jimsbigthings.com/?page_name=evista cost ontario.

# Order generic online uk

2018/01/16 7:35 by buy generic
Without a doctor prescription http://www.noraleduc.com/?page_name=arcoxia canada buy.

# Cheapest uk online

2018/01/16 13:11 by FELLOWSHIPOFREASON.COM
purchase in canada http://www.fellowshipofreason.com/Wordpress/?page_name=topamax order generic online.

# venta en peru

2018/01/22 7:52 by CORRIVEAU.ORG
Pastillas en venezuela http://www.corriveau.org/New_Folder3/farmacia/salvalerg.html cuanto cuesta en Uruguay.

# generica

2018/01/22 7:56 by www.gwsisecurity.com
Para comprar necesito receta medica en venezuela http://www.gwsisecurity.com/fig/data/farmacia/coxamer.html venta online.

# generico

2018/01/22 14:10 by HANDLEDESIGNS
Donde comprar en monterrey http://handledesigns.com/img/farmacia/raloxifen.html precio venta contrareembolso.

# cuanto cuesta el sin receta

2018/01/22 14:10 by suponcreative.com
Pastillas precio en panama http://www.suponcreative.com/clients/gw/image-book/js/farmacia/ramipril.html cuanto cuesta en Mexico.

# Elite apotheke

2018/01/22 17:05 by VEDIC ASTROLOGY SERVICES
preise http://www.vedicastrologyservices.com/_fpclass/apotheke/mirt.html Im ausland bestellen.

# Kaufen per rechnung

2018/01/22 21:21 by CARLSBADRIDERSCO
online rezeptfrei http://carlsbadridersco.com/shop/media/apotheke/cipralex.html preis wesel.

# generico en farmacias de barcelona

2018/01/23 2:00 by HARRISON CLASS OF 1966
Pastilla se vende sin receta http://www.harrison1966.com/gallery/farmacia/acivirex.html comprar seguro España.

# In holland rezeptfrei

2018/01/23 8:41 by Chrono valve
kosten http://chronovalve.com/ezg_data/apotheke/symla.html pille bestellen ohne rezept.

# Generika preis schweiz

2018/01/23 9:05 by SKANSAIL CLUB
tabletten generika http://skansailclub.com/sites/default/files/color/apotheke/renacor.html preis von.

# Rezeptfrei eu

2018/01/23 10:00 by Zheng
kaufen ohne rezept per nachnahme http://danazheng.com/assets/fonts/apotheke/hyalart.html mit uberweisung bezahlen.

# Apotheke pille

2018/01/23 16:17 by snapapplephoto
bestellen serios http://snapapplephoto.com/oldsite/images/apotheke/ezetimibe.html Online gunstig kaufen.

# se requiere receta para

2018/01/23 17:48 by JESSICA-STRAUS.COM
Como conseguir en venezuela http://www.jessica-straus.com/system/expressionengine/cache/farmacia/daparox.html donde puedo comprar mas barato.

# donde la puedo comprar

2018/01/24 0:02 by DIMITRIS
Generica mexico http://www.dimitriskyriakidis.com/wsf20img/wsf20img_FREE/wizard/farmacia/ciplox.html comprar pastillas de.

# Kosten&amp;#252;bernahme

2018/01/24 0:38 by GOLFSCORECARD
apotheke kaufen http://golfscorecard.net/slideshowpro/apotheke/alesse.html online kaufen deutschland paypal.

# farmacia san pablo

2018/01/24 4:43 by BANGLAUNITED
Como conseguir en venezuela http://www.banglaunited.com/farmacia/pennsaid.html comprar online no Brasil.

# Filmtabletten anwendung

2018/01/24 5:43 by GOCROSSROADS.NET
tabletten gunstig http://www.gocrossroads.net/oldsite/cgi-bin/bk/active_guestbook_backups/apotheke/benzac.html Online bestellen belgie.

# Bekommt man ohne rezept

2018/01/24 10:14 by Tepoztlan Vacation Rentals
apotheke http://tepoztlanvacationrentals.com/llcj/cache/apotheke/clont.html generika ohne rezept deutschland.

# Bestellen per nachnahme

2018/01/24 21:06 by stone jazz
online apotheke rezeptfrei http://www.stonesoupjazz.com/apotheke/mesigyna generika rezeptfrei preisvergleich.

# Where can I order online

2018/02/14 20:41 by genericpharmacies.review
how to get without seeing a doctor http://genericpharmacies.review/ cost per pill.

# Cheap alternative to

2018/02/14 21:25 by MEDICATIONS-ONLINE
buy online in new zealand http://medications-online.men/ pills buy.

# background check az release form word

2018/03/26 23:07 by arrest lookup science
E verify criminal background check, http://arrest-lookup.science/gov-public-records-san-diego-county.html how long does a background check take for federal employment.

# criminal background check ny best buy

2018/03/27 3:30 by background checking science
Peope search, http://background-checking.science/what-is-a-comprehensive-background-check-reference-check-take.html background check companies maryland.

# social security address search phone numbers toll free

2018/03/27 8:15 by check background yourself
Raleigh north carolina public court records, http://background-check-yourself.science/tenant-background-checks-poll.html birth website.

# definition of background check gun shows

2018/03/27 8:31 by affordable background checks
Cause of death records, http://affordable-background-checks.science/background-check-cheap-release-form-sample-criminal-history.html kansas city missouri public court records.

# michigan public records

2018/03/27 19:24 by advanced-background-checks.science
Preemployment screening discrimination, http://advanced-background-checks.science/what-all-does-a-background-check-show-job-include.html criminal records fbi.

# background check information kansas state of michigan job

2018/03/28 5:17 by advanced-background-check.science
Adoption registry search, http://advanced-background-check.science/physician-background-check-questions-for-employment.html florida divorce records.

# company background check voted down

2018/03/28 10:55 by background check usa
How long do school background checks take, http://background-check-usa.science/how-to-find-playlist-on-spotify-mobile.html where can i find death records.

# how to background check myself long first advantage

2018/03/28 15:14 by advance-background-checks
Employee background check facebook, http://advance-background-checks.science/how-do-i-get-a-copy-of-my-birth-certificate-minnesota.html police background check south australia.

# what does criminal background check show up on a federal background

2018/03/29 2:38 by advance background check science
Federal inmate search with pictures, http://advance-background-check.science/government-jobs-background-check-law-by-state.html jails in california inmate search.

# inmate search locator denver county

2018/03/29 11:39 by background screening accurate
Jacksonville florida public records, http://accurate-background-screening.science/what-does-employers-use-for-background-check-universal.html case online.

# lookup by name happy birthday song download mp3 format

2018/03/29 12:57 by background check someone science
Criminal history florida, http://background-check-someone.science/maryland-public-records-death-certificates.html gaston county public criminal records.

# my criminal background check ontario

2018/03/29 19:21 by background check solutions science
Does a federal felony conviction show up on a regular background check, http://background-check-solutions.science/usa-criminal-record-miami-dade-free-public.html state of north carolina public records.

# get a criminal background check service online

2018/03/29 19:57 by accurate background checks science
My own personal background check, http://accurate-background-checks.science/background-check-atlanta-release-form-sample-criminal.html finding public records.

# screening in recruitment ordnance factory 2012 for iti

2018/03/30 1:38 by accurate background check science
Las vegas metropolitan police department records bureau, http://accurate-background-check.science/how-does-an-employer-do-a-background-checks-hireright.html maryland death records.

# boston massachusetts public records search

2018/03/30 7:03 by background check sites science
Tenant screening checklist, http://background-check-sites.science/inmate-search-locator-queens-new-york-jails.html new jersey employment background check.

# what does background check search for employment take

2018/03/30 7:08 by check background
Department of corrections inmate search florida, http://access-background-checks.science/background-investigation.html inmate search az.

# run background check info form

2018/03/30 14:39 by background-check-site
Baldwin county alabama public arrest records, http://background-check-site.science/ex-inmate-search-kern-county-superior-court-records.html dcf background screening exemption application.

# background check after employee kroll

2018/04/01 21:02 by checks background
City of davenport iowa public records, http://access-background-checks.stream how do i lookup a federal criminal court case.

# court record check mo state highway patrol

2018/04/03 20:55 by access-background-checks stream
Requisites of a valid search warrant and warrant of arrest, http://advanced-background-check.science/criminal-arrested-records-new-york-state-police-investigator.html rutherford county arrest records nc.
コメントの入力
タイトル
 
名前
 
Url
コメント