카테고리 없음
URL 접근
Binsoo
2021. 2. 24. 16:19
728x90
반응형
/**
* [ 1 ] API 를 호출하여 DATA 를 가져옴
*/
public List<Demon_Test_VO> api_Get_Data_1( String strUrl ) {
List<Demon_Test_VO> list = new ArrayList<Demon_Test_VO>();
String json = send_Post(strUrl);
JSONObject jsonObject = new JSONObject(json);
JSONArray jsonArray = jsonObject.getJSONArray("docs");
int length = jsonArray.length();
for( int i=0; i<length; i++ ) {
Demon_Test_VO vo = new Demon_Test_VO();
JSONObject tempObject = jsonArray.getJSONObject(i);
vo.setI_content(tempObject.getString("i_content"));
vo.setI_title(tempObject.getString("i_title"));
list.add(vo);
}
return list;
}
/**
* API 를 호출하여 DATA 생성
*/
private String send_Post(String strUrl) {
try{
// URL 연결
URL url = new URL(strUrl);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
// 지연 방지
httpURLConnection.setConnectTimeout(5000);
httpURLConnection.setReadTimeout(5000);
// 설정
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setRequestProperty("Content-Type", "application/json");
// Server 통신에서 출력 가능한 상태
httpURLConnection.setDoOutput(true);
// 캐싱데이터의 캐치 유무
httpURLConnection.setUseCaches(false);
StringBuffer stringBuffer = new StringBuffer();
if(httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
BufferedReader br = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream(), "utf-8"));
String line;
while( (line = br.readLine() ) != null ) {
stringBuffer.append(line).append("\n");
}
br.close();
return stringBuffer.toString();
}else {
return httpURLConnection.getResponseMessage();
}
}catch (Exception e) {
e.printStackTrace();
return null;
}
}
728x90
반응형