LoginSignup
0
0

More than 5 years have passed since last update.

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

Last updated at Posted at 2013-09-17

リクエストパラメータに日本語が使用できなかったのでURLエンコードをかける

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

def cbMethod
def txtUrl
def txtParam
def txtJson

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 = {
    def method = cbMethod.selectedItem
    def url = txtUrl.text
    def params = URLEncoder.encode(txtParam.text, 'utf-8').replaceAll('%3D', '=').replaceAll('%26', '&')
    if (method == 'GET') {
        url = "${url}?${params}"
    }

    def conn = url.toURL().openConnection()
    conn.requestMethod = cbMethod.selectedItem
    if (method == 'POST') {
        conn.doOutput = true
        conn.outputStream << txtParam.text
    }

    txtJson.text = 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) {
        cbMethod = comboBox(items:['GET', 'POST'])
        txtUrl = textField()
        button(text:'送信', actionPerformed:sendRequest)
    }
    tabPane = tabbedPane(constraints: BorderLayout.CENTER) {
        scrollPane(name:'パラメータ') {
            txtParam = textArea()
        }
        scrollPane(name:'レスポンス') {
            txtJson = textArea(editable:false)
        }
    }
}
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