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();
}
}
}
'JAVA' 카테고리의 다른 글
소수점 자리수 정해서 버림. 0단위도 표기할것. (0) | 2015.04.13 |
---|---|
String int 형변환 _ 음수인식 (0) | 2015.01.04 |
스트링형 파라메터는 비교문 적용이 안될때 Trim() 한번 해주자. (0) | 2015.01.04 |
String to Date 문자열날짜를 날짜형으로 바꾸기 (0) | 2015.01.04 |
Java Date 관련 간단한 예제. _ 자바 날짜 생일 현재 (0) | 2015.01.04 |