자바(Java)
자바 json http 호출 하고 응답 받는 아주 간단한 소스
xemaker
2023. 2. 27. 14:57
자바 json http 호출 하고 응답 받는 아주 간단한 소스를 소개합니다.
json으로 요청 파라미터를 구성해서 요청하고 json으로 응답을 받습니다.
public class Https{
final static String clientId="adf";
final static String clientSecret="dfas";
final static String id="aa";
final static String password="bb";
public static void main(String[] args) throws Exception{
Https https=new Https();
String targetUrl="http://aa.com";
URL url=new URL(targetUrl);
HttpURLConnection con(HttpURLConnection)url.openConnection();
con.setRequestProperty("Content-Type", "application/json;utf-8");
con.setDoOutput(true);
JSONObject json=new JSONObject();
JSONObject jsonCommon=new JSONObject();
JSONObject jsonData=new JSONObject();
jsonCommonput("clientId", clientId);
jsonData.put("password", password);
json.put("common",jsonCommon");
json.put("data",jsonData");
//위에는 사정에 맞게 넣으면 된다.
try(OutputStream os=con.getOutputStream()){
byte[] input=j.getBytes("utf-8");
os.write(input, 0, input.length);
}
int responseCode=con.getResponseCode();
System.out.println("응답코드:"+responseCode);
String rst="";
try(BufferedReader reader=new BufferedReader(new InputStreamReader(con.getInputStream(), "utf-8"))){
StringBuilder response=new StringBuilder();
String inputLine=null;
while((inputLine=br.readLine())!=null){
response.append(inputLine);
}
rst=response.toString();
}
JSONParser jsonParser=new JSONParser();
JSONObject jsonObject=(JSONObject) jsonParser.parse(rst);
JSONObject joData=(JSONObject)jsonObject.get("data");
// 각자의 사정에 맞게 하면된다.
}
USER_AGENT라고 있는데 없어도 된다. 그래서 여기 소스에는 넣지 않았다.
만약 targetUrl이 잘못되었다면
java.io.FileNotFoundException: https://aa
만약 con.setRequestProperty 부분이 잘못되었다면
한참 후에
java.io.IOException: Server returned HTTP response code : 500 for URL : https://