티스토리 뷰

Language/JAVA

http 통신

각인 2021. 11. 24. 16:13

GET 방식 요청

try{
    CloseableHttpClient httpClient = HttpClients.custom()
                                    .setSSLContext(sslcontext.build())
                                    .setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
                                    .build();

    String url = "https://..."; //요청할 주소
    HttpGet httpGet = new HttpPost(url);
    
    url+="?param1=data1&pram2=data2..."; // 넘길 데이터 예제
    
    CloseableHttpResponse response = httpClient.execute(httpGet);
    response.close();
    httpClient.close();
    
  }catch (Exception e){
  	e.printStackTrace();
    
  }

 

POST 방식 요청

try{
    SSLContextBuilder sslcontext = new SSLContextBuilder(); //https 의 경우
    sslcontext.loadTrustMaterial(null, new TrustSelfSignedStrategy());
    CloseableHttpClient httpClient = HttpClients.custom()
                                    .setSSLContext(sslcontext.build())
                                    .setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
                                    .build();

    String url = "https://..."; //요청할 주소
    HttpPost httpPost = new HttpPost(url);
    httpPost.setHeader("Content-Type", "application/json");
     
    //넘길 데이터 예제
    //방식1
    String data = "{'param1':'data1', 'param':'data2'}"; 
    
    //방식2
    //HashMap<String, Object> data = new HashMap<String, Object>();
    //data.put("param1", "data1");
    
    //방식3
    //ExampleVo data = new ExampleVo();
    //data.setParam1("data1");
	
    ObjectMapper mapper = new ObjectMapper();
    String jsonStr = mapper.writeValueAsString(data);
	StringEntity strEnt = new StringEntity(jsonStr);
	httpPost.setEntity(strEnt);
    CloseableHttpResponse response = httpClient.execute(httpPost);
    response.close();
    httpClient.close();
    
  }catch (Exception e){
  	e.printStackTrace();
    
  }
댓글
공지사항
최근에 올라온 글