1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

HttpURLConnectionでCookieの取得、使用

Last updated at Posted at 2015-01-06

はじめに

CookieHandlerとかCookieManagerとかあったが上手く使いこなせなかった・・・
なのでgetHeaderFieldsでCookieを取得しています。

やりたいこと

  • ニコニコ動画にログインしてCookieの取得
  • apiを叩いて結果取得

ソースコード(Cookie取得部分のみ)

NicoAuth.scala
package auth

import java.io.PrintStream
import java.net._
import javax.net.ssl.HttpsURLConnection
import scala.util.control.NonFatal

import scala.collection.JavaConversions._
/**
 * Created by FScoward on 15/01/05.
 */
object NicoAuth {

  def authenticate(mail: String, password: String): Option[Cookie] = {

    val loginUrl = "https://secure.nicovideo.jp/secure/login?site=niconico"

    try{
      val connect = new URL(loginUrl).openConnection().asInstanceOf[HttpsURLConnection]
      // POST可能にする
      connect.setDoOutput(true)

      val outputStream = connect.getOutputStream
      // postするデータの作成
      val postData = s"mail=$mail&password=$password"
      val printStream = new PrintStream(outputStream)

      // データをpostする
      printStream.print(postData)
      printStream.close()

      // postした結果の取得
      connect.getInputStream
      val cookie = connect.getHeaderFields.get("Set-Cookie").filter(_.matches("user_session=user_session.*")).mkString.split(";")

      // case classにぶちこむ
      Option(
        Cookie(
          cookie(0),//.replace("user_session=", ""),
          cookie(1),//.replace("expires=", ""),
          cookie(2),//.replace("path=", ""),
          cookie(3)//.replace("domain=", "")
        ))
    } catch {
      case NonFatal(e) => None
    }
  }
}

実行結果

スクリーンショット 2015-01-06 23.42.46.png

結果の一部をデコード

765プロなんだしミリ うぽーつ オワタン&#x30b4w; 最高の娯楽・涼ちん.. ","length":"12:17","title_short":"【アイマス】歌姫ペダル PCM2013 (41)","description_short":"あけましておめでとうございます。今年も動画編集頑張っていきたいと思います。&#x524dsm25154617; ?/21(水)0:00予定マイリスト:mylist/39561422コミュ:co372085Twitter:xs...","thumbnail_style":null,"is_middle_thumbnail":true}],"count":38067,"has_ng_video_for_adsense_on_listing":true,"related_tags":["iM@S架空戦記","iM@S架空戦記シリーズ","iM@S架空戦&#x8a18Part1;","iM@S架空戦記支援","iM@S架空戦記最終回リンク","iM@S架空戦記ウ&#x30bdPart1;","iM@S架空戦&#x8a18OP;�リンク","iM@S架空戦&#x8a18Part0;","iM@S架空戦記一発ネタ","iM@S架空戦記ランキング

全容

1
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?