-
Tech Note 정보
-
라그나로크 님이 작성하신 글입니다.
-
카테고리: [ Java ]
-
-
-
-
조회수: 17769
1. 코드
import org.json.JSONException;
import org.json.JSONObject;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class Exchange {
private static final String HOST_URL = <API 주소>;
public void get() {
HttpURLConnection conn = null;
JSONObject responseJson = null;
try {
URL url = new URL(HOST_URL);
conn = (HttpURLConnection)url.openConnection();
conn.setConnectTimeout(5000);
conn.setReadTimeout(5000);
conn.setRequestMethod("GET");
//conn.setDoOutput(true);
JSONObject commands = new JSONObject();
int responseCode = conn.getResponseCode();
if (responseCode == 400 || responseCode == 401 || responseCode == 500 ) {
System.out.println(responseCode + " Error!");
} else {
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = "";
while ((line = br.readLine()) != null) {
sb.append(line);
}
responseJson = new JSONObject(sb.toString());
System.out.println(responseJson);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
System.out.println("not JSON Format response");
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}