GET 방식처리

다음과 같은 방법으로 웹페이지에 접속하여 해당 웹 자원을 읽어낼 수 있다.



import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.net.MalformedURLException;

import java.net.URL;

 

/**

 * @author Steven J.S Min

 *

 */

public class URLStreamDataTest {

 

       /**

        * @param args

        */

       public static void main(String[] args) {

 

              try {

                     URL url = new URL("http://www.naver.com/index.html");

                     BufferedReader bin = new BufferedReader(new InputStreamReader(url.openStream()));

 

                     String line;

                     while ((line = bin.readLine()) != null) {

                           System.out.println(line);

                     }

                     bin.close();

 

              } catch (MalformedURLException e) {

                     e.printStackTrace();

              } catch (IOException e) {

                     e.printStackTrace();

              }

 

       }

 

}

 

 

URLConnection 통해 Connection 하면URLConnection 객체를 통해 부가정보를 얻을 있겠다.

  

URL url = new URL("http://www.naver.com/index.html");

 

URLConnection connection = url.openConnection();

 

String mimeType = connection.getContentType();

 

connection.setConnectTimeout(1000); // Timeout 설정

connection.setReadTimeout(10000); // Read Timeout 설정

InputStream in = connection.getInputStream();

 

 

POST 방식처리

다음은 Name필드와 Password 필드를 POST방식으로 전송한는 예이다.

 

import java.awt.Component;

import java.awt.GridBagConstraints;

import java.awt.GridBagLayout;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.io.IOException;

import java.io.OutputStreamWriter;

import java.io.PrintWriter;

import java.net.HttpURLConnection;

import java.net.MalformedURLException;

import java.net.URL;

import java.net.URLEncoder;

 

import javax.swing.BorderFactory;

import javax.swing.JButton;

import javax.swing.JFrame;

import javax.swing.JLabel;

import javax.swing.JPanel;

import javax.swing.JPasswordField;

import javax.swing.JTextField;

 

public class Post extends JPanel implements ActionListener {

       JTextField nameField, passwordField;

       String postURL;

 

       GridBagConstraints constraints = new GridBagConstraints();

 

       void addGB(Component component, int x, int y) {

              constraints.gridx = x;

              constraints.gridy = y;

              add(component, constraints);

       }

 

       public Post(String postURL) {

 

              this.postURL = postURL;

 

              setBorder(BorderFactory.createEmptyBorder(5, 10, 5, 5));

              JButton postButton = new JButton("Post");

              postButton.addActionListener(this);

              setLayout(new GridBagLayout());

              constraints.fill = GridBagConstraints.HORIZONTAL;

              addGB(new JLabel("Name ", JLabel.TRAILING), 0, 0);

              addGB(nameField = new JTextField(20), 1, 0);

              addGB(new JLabel("Password ", JLabel.TRAILING), 0, 1);

              addGB(passwordField = new JPasswordField(20), 1, 1);

              constraints.fill = GridBagConstraints.NONE;

              constraints.gridwidth = 2;

              constraints.anchor = GridBagConstraints.EAST;

              addGB(postButton, 1, 2);

       }

 

       public void actionPerformed(ActionEvent e) {

              postData();

       }

 

       protected void postData() {

              StringBuffer sb = new StringBuffer();

              sb.append(URLEncoder.encode("Name") + "=");

              sb.append(URLEncoder.encode(nameField.getText()));

              sb.append("&" + URLEncoder.encode("Password") + "=");

              sb.append(URLEncoder.encode(passwordField.getText()));

              String formData = sb.toString();

 

              try {

                     URL url = new URL(postURL);

                     HttpURLConnection urlcon = (HttpURLConnection) url.openConnection();

                     urlcon.setRequestMethod("POST");

                     urlcon.setRequestProperty("Content-type", "application/x-www-form-urlencoded");

                     urlcon.setDoOutput(true);

                     urlcon.setDoInput(true);

                     PrintWriter pout = 

                          new PrintWriter(new OutputStreamWriter(urlcon.getOutputStream(), "8859_1"), true);


                     pout.print(formData);

                     pout.flush();

 

                     // read results...

                     if (urlcon.getResponseCode() != HttpURLConnection.HTTP_OK) System.out.println("Posted ok!");

                     else {

                           System.out.println("Bad post...");

                           return;

                     }

                     // InputStream in = urlcon.getInputStream( );

                     // ...

 

              } catch (MalformedURLException e) {

                     System.out.println(e); // bad postURL

              } catch (IOException e2) {

                     System.out.println(e2); // I/O error

              }

       }

 

       public static void main(String[] args) {

              JFrame frame = new JFrame("SimplePost");

              frame.add(new Post(args[0]), "Center");

              frame.pack();

              frame.setVisible(true);

       }

}

 


실행방법

% java Post http://www.myserver.example/cgi-bin/login.cgi


'Java > Java for the Web' 카테고리의 다른 글

Web-Service Sample  (0) 2013.11.16
Filtering the Servlet Request & Response  (0) 2013.02.12
A Simple Filter  (0) 2013.02.12
Cookie정보 보기  (0) 2013.02.12
Session정보 보기  (0) 2013.02.12
Posted by Steven J.S Min
,