JAVA/JAVA__Works

HttpURLConnection + GET + api 호출하기

말하는감자 2020. 5. 15. 14:14
application.yml
api:
  test:
    url: 'http://localhost:8080/api'
 
ApiInvokeService.java
@Autowired
public ApiService(@Value("${api.test.url}" String apiUrl) {
    this.apiUrl = apiUrl;
}

public List<ApiDto> apiInvoke(String userId) {
    List<ApiDto> apiList = new ArrayList<>();
    URL url = new URL(apiUrl + URLEncoder.encode(userId, "UTF-8") + "call");
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setUseCaches(false);
    conn.setRequestMethod("GET");
    conn.setRequestProperty("Content-Type", "application/json");
    BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));

    String inputLines = null;
    StringBuffer sb = new StringBuffer();
    while ((inputLines = in.readLine() != null) {
        sb.append(inputLines);
    }
    ApiList.add(sb);
}

'JAVA > JAVA__Works' 카테고리의 다른 글

ModelMap Return  (0) 2020.05.15
SimpleDateFormat  (0) 2020.05.15
list, map  (0) 2019.06.12