0
0

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.

jsonを取得、表示するアプリケーション その8

Posted at

毎回URLConnectionを開き直してるのでセッション管理で発行されるCookieが維持できない
なのでCookieManagerを使ってCookieを受け入れるようにする

json_client.groovy
import groovy.swing.SwingBuilder
import groovy.json.JsonOutput
import groovy.beans.Bindable
import javax.swing.*
import java.awt.*
import java.net.*

def manager = new CookieManager()
manager.cookiePolicy = CookiePolicy.ACCEPT_ALL
CookieHandler.default = manager

@Bindable
class Model {
	String method = 'GET'
	String url = ''
	String params = ''
	String json = ''
}
def model = new Model()

def tabPane

def prettyPrint = { text ->
	def result = JsonOutput.prettyPrint(text)
	(result =~ /\\u[0-9a-zA-Z]{4}/).each { match ->
		def code = match[2..5]
		def encTxt = new String([Integer.parseInt(code, 16)] as int[], 0, 1)
		result = result.replaceAll(/\\u${code}/, encTxt)
	}
	result
}

def sendRequest = {
	model.json = ''
	
	def method = model.method
	def url = model.url
	def params = URLEncoder.encode(model.params, 'utf-8').replaceAll('%3D', '=').replaceAll('%26', '&')
	if (method == 'GET') {
		url = "${url}?${params}"
	}
	
	def conn = url.toURL().openConnection()
	conn.requestMethod = method
	if (method == 'POST') {
		conn.doOutput = true
		conn.outputStream << params
	}
	
	model.json = prettyPrint(conn.inputStream.getText('utf-8'))
	tabPane.selectedIndex = 1
}

new SwingBuilder().frame(title:'jsonを取得、表示するアプリケーション', defaultCloseOperation:JFrame.EXIT_ON_CLOSE,
						size: [800, 600], show:true) {
	lookAndFeel('nimbus')
	borderLayout()
	hbox(constraints: BorderLayout.NORTH) {
		comboBox(items:['GET', 'POST'], selectedItem:bind(source: model, sourceProperty: 'method', mutual: true))
		textField(text:bind(source: model, sourceProperty: 'url', mutual: true))
		button(text:'送信', actionPerformed:sendRequest)
	}
	tabPane = tabbedPane(constraints: BorderLayout.CENTER) {
		scrollPane(name:'パラメータ') {
			textArea(text:bind(source: model, sourceProperty: 'params', mutual: true))
		}
		scrollPane(name:'レスポンス') {
			textArea(editable:false, text:bind {model.json})
		}
	}
}

qiita-008.png

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?