HTTPリクエストをGUIアプリケーションから送信しレスポンスを表示する
戻る
::::::::::::::
ClientPointEmulator.java
::::::::::::::
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
/**
* $Id: CPE.html,v 1.1 2009/06/22 16:11:40 kishi Exp kishi $
* @author KISHI Yasuhiro
*/
public class ClientPointEmulator extends JFrame {
private RequestView requestView;
private ResponseView responseView;
/**
* メインメソッド
*/
public static void main( String[] args ) {
new ClientPointEmulator();
}
/**
* コンストラクタ
*/
public ClientPointEmulator() {
super( "GCPのエミュレーション" );
// パネルをコンテナに配置
requestView = new RequestView();
responseView = new ResponseView();
Container container = getContentPane();
container.setLayout( new BoxLayout( container, BoxLayout.PAGE_AXIS ) );
container.add( requestView );
container.add( responseView );
try {
MyObservable.getInstance().addObserver( responseView );
} catch ( Exception e ) {
e.printStackTrace();
}
setDefaultCloseOperation( EXIT_ON_CLOSE );
setBounds( 0, 0, 500, 720 );
setVisible( true );
// pack();
}
}
::::::::::::::
HTTPClient.java
::::::::::::::
import java.io.*;
import java.util.*;
import java.net.*;
/**
* $Id: CPE.html,v 1.1 2009/06/22 16:11:40 kishi Exp kishi $
*/
public class HTTPClient {
final private String USER_AGENT = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.0.3705; .NET CLR 1.1.4322)" ;
private String urlString;
private String request;
private String response;
/**
* コンストラクタ
* @param urlString URL文字列
* @param request 送信電文
*/
public HTTPClient( String urlString, String request ) throws Exception {
URL url = null;
try {
url = new URL( urlString );
// URLにアクセス
URLConnection conn = url.openConnection();
conn.setDoOutput( true );
// HTTPヘッダにUSER-AGENTを追加 -- IEにしてしまいます
conn.setRequestProperty( "User-Agent", USER_AGENT );
//=============================
// 送信電文を書き込む
//=============================
PrintStream ps =
new PrintStream( conn.getOutputStream() );
ps.print( request );
ps.flush();
ps.close();
ps = null;
//=============================
// 返信電文を読む
//=============================
BufferedReader reader =
new BufferedReader(
new InputStreamReader(
conn.getInputStream() ) );
// System.out.println( "--- RESPONSE ---" );
String line;
StringBuilder sb = new StringBuilder();
while ( ( line = reader.readLine() ) != null ) {
// System.out.println( line );
sb.append( line + "\n" );
}
reader.close();
reader = null;
response = sb.toString();
} catch ( Exception e ) {
throw e;
}
}
/**
* 返信電文を取得する
* @return 返信電文
*/
public String getResponse() {
return response;
}
/**
* 単体試験
*/
public static void main( String[] args ) {
if ( args.length != 1 ) {
System.err.println( "java -cp . HTTPClient [url]" );
System.exit( 1 );
}
try {
HTTPClient client = new HTTPClient( args[ 0 ], "テスト" );
System.out.println( client.getResponse() );
} catch ( Exception e ) {
e.printStackTrace();
}
}
}
::::::::::::::
MyObservable.java
::::::::::::::
import java.io.*;
import java.util.*;
/**
* $Id: CPE.html,v 1.1 2009/06/22 16:11:40 kishi Exp kishi $
* シングルトンにしなければならない
*/
public class MyObservable extends Observable {
private static MyObservable uniqueInstance = null;
public static MyObservable getInstance() throws Exception {
if ( uniqueInstance == null ) {
uniqueInstance = new MyObservable();
System.out.println( uniqueInstance.getClass().getName() + " がインスタンス化されました。" );
}
return uniqueInstance;
}
public void castUpdateMessage( String message ) {
setChanged();
notifyObservers( message );
}
}
::::::::::::::
RequestView.java
::::::::::::::
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
/**
* $Id: CPE.html,v 1.1 2009/06/22 16:11:40 kishi Exp kishi $
*/
public class RequestView extends JPanel implements ActionListener {
/**
* 送信ボタン
*/
private JButton submitButton;
/**
* クリアボタン
*/
private JButton clearButton;
private JTextArea messageTA;
private JTextField urlTF;
private JComboBox timeoutCB;
public RequestView() {
//--------------------------------------------------------------
// this.setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
// this.add( new JLabel( "■HTTPリクエスト", JLabel.LEFT ) );
//--------------------------------------------------------------
// URLを入力するエリア
JPanel urlPanel = new JPanel();
urlPanel.add( new JLabel( "URL: " ) );
urlTF = new JTextField( 30 );
urlPanel.add( urlTF );
this.add( urlPanel );
// 送信電文を書き込むテキストエリア
JScrollPane scrPane = new JScrollPane();
scrPane.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_ALWAYS );
messageTA = new JTextArea();
messageTA.setToolTipText( "ここに送信電文を書き込みます" );
scrPane.getViewport().setView( messageTA );
scrPane.setPreferredSize( new Dimension( 400, 200 ) );
this.add( scrPane );
// 送信ボタン、クリアボタンを配置するパネル
JPanel operationPanel = new JPanel();
submitButton = new JButton( "送信" );
clearButton = new JButton( "クリア" );
submitButton.addActionListener( this );
submitButton.setActionCommand( "SUBMIT" );
clearButton.addActionListener( this );
clearButton.setActionCommand( "CLEAR" );
timeoutCB = new JComboBox( new Object[] {10, 20, 30, 40, 50, 60} );
operationPanel.add( submitButton );
operationPanel.add( clearButton );
operationPanel.add( new JLabel( "Timeout:" ) );
operationPanel.add( timeoutCB );
this.add( operationPanel );
}
public void actionPerformed( ActionEvent evt ) {
String command = evt.getActionCommand();
System.out.println( "COMMAND: " + command );
if ( "SUBMIT".equals( command ) ) {
Runnable runnable = new Runnable() {
public void run() {
submitButton.setEnabled( false );
try {
TimeoutPropertyManager.doSet( ( timeoutCB.getSelectedItem() ).toString() + "000" );
HTTPClient client = new HTTPClient( urlTF.getText(), messageTA.getText() );
System.out.println( client.getResponse() );
System.out.println( timeoutCB.getSelectedItem() );
// メッセージをObserverに通知
MyObservable.getInstance().castUpdateMessage( client.getResponse() );
} catch ( Exception e ) {
e.printStackTrace();
} finally {
submitButton.setEnabled( true );
}
}
};
Thread thread = new Thread( runnable );
thread.start();
}
if ( "CLEAR".equals( command ) ) {
messageTA.setText( "" );
}
}
}
::::::::::::::
ResponseView.java
::::::::::::::
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
/**
* $Id: CPE.html,v 1.1 2009/06/22 16:11:40 kishi Exp kishi $
*/
public class ResponseView extends JPanel implements Observer {
private JTextArea messageTA;
public ResponseView() {
super();
setBackground( new Color( 0x66, 0x00, 0xff ) );
// 返信電文を表示するテキストエリア
JScrollPane scrPane = new JScrollPane();
messageTA = new JTextArea();
messageTA.setForeground( Color.white );
messageTA.setBackground( Color.black );
scrPane.getViewport().setView( messageTA );
scrPane.setPreferredSize( new Dimension( 450, 320 ) );
this.add( scrPane );
JPanel summaryPanel = new JPanel();
summaryPanel.add( new JLabel( "応答時間:" ) );
this.add( summaryPanel );
}
public void update( Observable obj, Object arg ) {
System.out.println( this.getClass().getName() + ": update()" );
//System.out.println( "メッセージは、" + arg );
messageTA.setText( arg.toString() );
}
}
::::::::::::::
TimeoutPropertyManager.java
::::::::::::::
import java.util.*;
/**
<pre>
$Id: CPE.html,v 1.1 2009/06/22 16:11:40 kishi Exp kishi $
Timeoutなどのプロパティをセットする
</pre>
@author KISHI Yasuhiro
*/
public class TimeoutPropertyManager {
/**
* @param param ミリ秒
*/
static public void doSet( String param ) {
/******************************************************************************/
/* 接続タイムアウトの設定; 設定された時間でコネクトできない場合はタイムアウト */
/******************************************************************************/
System.setProperty ( "sun.net.client.defaultConnectTimeout", param );
/**********************************************************************************/
/* 読み取りタイムアウトの設定; 設定された時間で読み取りできない場合はタイムアウト */
/**********************************************************************************/
System.setProperty ( "sun.net.client.defaultReadTimeout", param );
}
}
戻る