티스토리 뷰

자바 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://

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/02   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28
글 보관함