'HttpURLConnection'에 해당되는 글 2건
- 2021.08.06 [java] HttpURLConnection - GET/POST
- 2021.06.09 API요청&응답 받아오기 - HttpURLConnection 사용법
320x100
[java] HttpURLConnection - GET/POST
Posted on 2021. 8. 6. 13:23
Filed Under Programming/Java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.codehaus.jettison.json.JSONObject;
//▼HTTP Reqeust GET/POST 샘플 코드
private String charsetName = "UTF-8";
// Open API 호출 테스트 샘플
public String testGET() throws Exception
{
//JSONObject obj = new JSONObject();
String baseUrl = "http://data.ex.co.kr/openapi/restinfo/restWeatherList?key=0759277880&type=json&sdate=20210507&stdHour=12";
String resultJSON = "{}";
try {
URL url = new URL(baseUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("GET");
conn.setRequestProperty("Content-type", "text/html; charset="+charsetName);
// conn.setRequestProperty("Authorization", "Basic 암호화한인증키");
// conn.setRequestProperty("Accept","*/*");
// conn.setRequestProperty("Accept-Language","ko");
// conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
// conn.setRequestProperty("User-Agent","Mozilla/4.0");
// conn.setRequestProperty("Host", "서버IP:포트");
// conn.setRequestProperty("Connection","Keep-Alive");
// conn.setRequestProperty("Cookie", "바사삭~쿠키");
//
// conn.setDoOutput(true);
// conn.setDoInput(true);
// conn.setUseCaches(true);
//conn.setDoInput(true);
System.out.println(((HttpURLConnection)conn).getRequestMethod());
// OutputStreamWriter osw = new OutputStreamWriter(conn.getOutputStream(), "utf-8");
// osw.flush();
int httpResponseCode = conn.getResponseCode();
BufferedReader rd;
if(httpResponseCode >= HttpURLConnection.HTTP_OK && httpResponseCode <= HttpURLConnection.HTTP_MULT_CHOICE) {
rd = new BufferedReader(new InputStreamReader(conn.getInputStream(), charsetName));
} else {
rd = new BufferedReader(new InputStreamReader(conn.getErrorStream(), charsetName));
}
StringBuilder sb = new StringBuilder();
String line;
while ((line = rd.readLine()) != null) {
sb.append(line);
}
rd.close();
conn.disconnect();
resultJSON = sb.toString();
} catch (IOException e) {
e.printStackTrace();
}
return resultJSON;
}
public String testPOST() throws Exception
{
String baseUrl = "http://my-json-server.typicode.com/smallwitch/apitest/posts";
String result = "{}";
JSONObject jsonObj = new JSONObject();
try {
URL url = new URL(baseUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-type", "application/json");
OutputStreamWriter osw = new OutputStreamWriter(conn.getOutputStream(), charsetName);
jsonObj.put("id", 100);
Date date = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
jsonObj.put("title", dateFormat.format(date));
System.out.println("input: "+jsonObj.toString());
osw.write(jsonObj.toString());
osw.flush();
int httpResponseCode = conn.getResponseCode();
BufferedReader rd;
if(httpResponseCode >= HttpURLConnection.HTTP_OK && httpResponseCode <= HttpURLConnection.HTTP_MULT_CHOICE) {
rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
} else {
rd = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
}
StringBuilder sb = new StringBuilder();
String line;
while ((line = rd.readLine()) != null) {
sb.append(line);
}
rd.close();
conn.disconnect();
result = sb.toString();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
반응형
API요청&응답 받아오기 - HttpURLConnection 사용법
Posted on 2021. 6. 9. 15:42
Filed Under Programming/Java
// HttpURLConnection 객체 생성.
HttpURLConnection conn = null;
// URL 연결 (웹페이지 URL 연결.)
conn = (HttpURLConnection)url.openConnection();
// TimeOut 시간 (서버 접속시 연결 시간)
conn.setConnectTimeout(CONN_TIMEOUT * 1000);
// TimeOut 시간 (Read시 연결 시간)
conn.setReadTimeout(READ_TIMEOUT * 1000);
// 요청 방식 선택 (GET, POST)
conn.setRequestMethod(GET);
// Request Header값 셋팅 setRequestProperty(String key, String value)
conn.setRequestProperty("NAME", "name");
conn.setRequestProperty("MDN", "mdn");
conn.setRequestProperty("APPID", "appid");
// 서버 Response Data를 xml 형식의 타입으로 요청.
conn.setRequestProperty("Accept", "application/xml");
// 서버 Response Data를 JSON 형식의 타입으로 요청.
conn.setRequestProperty("Accept", "application/json");
// 타입설정(text/html) 형식으로 전송 (Request Body 전달시 text/html로 서버에 전달.)
conn.setRequestProperty("Content-Type", "text/html");
// 타입설정(text/html) 형식으로 전송 (Request Body 전달시 application/xml로 서버에 전달.)
conn.setRequestProperty("Content-Type", "application/xml");
// 타입설정(application/json) 형식으로 전송 (Request Body 전달시 application/json로 서버에 전달.)
conn.setRequestProperty("Content-Type", "application/json");
// 컨트롤 캐쉬 설정
conn.setRequestProperty("Cache-Control","no-cache");
// 타입길이 설정(Request Body 전달시 Data Type의 길이를 정함.)
conn.setRequestProperty("Content-Length", "length")
// User-Agent 값 설정
conn.setRequestProperty("User-Agent", "test");
// OutputStream으로 POST 데이터를 넘겨주겠다는 옵션.
conn.setDoOutput(true);
// InputStream으로 서버로 부터 응답을 받겠다는 옵션.
conn.setDoInput(true);
// Request Body에 Data를 담기위해 OutputStream 객체를 생성.
OutputStream os = conn.getOutputStream();
// Request Body에 Data 셋팅.
os.write(body.getBytes("euc-kr"));
// Request Body에 Data 입력.
os.flush();
// OutputStream 종료.
os.close();
// 실제 서버로 Request 요청 하는 부분. (응답 코드를 받는다. 200 성공, 나머지 에러)
int responseCode = conn.getResponseCode();
// 접속해지
conn.disconnect();
출처: [이용범의 잡다한 개발이야기]
반응형