SSISO Community

시소당

[URLConnection] 의 사용방법은?

URLConnection을 통하여 인자를 넘겨주고 싶습니다.

 

넘겨주고 싶은 인자  : String  inja = "인자";

넘길 주소                : String  ip = http://10.10.10.10:80/a.jsp;

 

 

URL sun = new URL(iip); 

URLConnection uc = sun.openConnection();

 

요기다가 어떻게 inja를 같이 넘겨줄 수 있나요?

 

 

 

------------------------------------------------

답변 주실분 정말정말 감사드리구요;;

감사의 표시로 작지만 내공 100점 드릴께요 ^^;;

 

즐거운 한 주 보내세요~~

------------------------------------------------

 

 

안녕 하세요..

 

아래에 소스 코드 첨부합니다.

 

 

import java.net.*;
import java.io.*;

 

public class TestURLConnection {
    public static void main(String[] args) {
        URL url = null;
        URLConnection urlConnection = null;
       
        // URL 주소
        String sUrl = "http://localhost/test.jsp

        // 파라미터 이름
        String paramName = "animal";

        // 파라미터 이름에 대한 값
        String paramValue = "dog";

 

        try {
            // Get방식으로 전송 하기
            url = new URL(sUrl + "?" + paramName + "=" + paramValue);
            urlConnection = url.openConnection();
            printByInputStream(urlConnection.getInputStream());
           
            // Post방식으로 전송 하기
            url = new URL(sUrl);
            urlConnection = url.openConnection();
            urlConnection.setDoOutput(true);
            printByOutputStream(urlConnection.getOutputStream(), paramName + "=" + paramValue);
            printByInputStream(urlConnection.getInputStream());
        } catch(Exception e) {
            e.printStackTrace();
        }
    }
   
    // 웹 서버로 부터 받은 웹 페이지 결과를 콘솔에 출력하는 메소드
    public static void printByInputStream(InputStream is) {
        byte[] buf = new byte[1024];
        int len = -1;
       
        try {
            while((len = is.read(buf, 0, buf.length)) != -1) {
                System.out.write(buf, 0, len);
            }
        } catch(IOException e) {
            e.printStackTrace();
        }
    }

 

    // 웹 서버로 파라미터명과 값의 쌍을 전송하는 메소드
    public static void printByOutputStream(OutputStream os, String msg) {
        try {
            byte[] msgBuf = msg.getBytes("UTF-8");
            os.write(msgBuf, 0, msgBuf.length);
            os.flush();
        } catch(IOException e) {
            e.printStackTrace();
        }
    }
}

3664 view

4.0 stars