본문 바로가기
개인적 정리

CURL & URLConnection

by 설이주인 2024. 6. 10.

CURL

https://everything.curl.dev/project/index.html

 

The cURL project - everything curl

A funny detail about Open Source projects is that they are called projects, as if they were somehow limited in time or ever can get done. The cURL project is a number of loosely coupled individual volunteers working on writing software together with a comm

everything.curl.dev

 

 

GET

curl -X GET "http://localhost:8000/hello?[parameter]=[value]"

 

POST

URL
curl -d "key1=value1&key2=value2" \
-H "Content-Type: application/x-www-form-urlencoded" \
-X POST http://localhost:8000/data


JSON
curl -d '{
"key2" : value2,
"key3" :  value3,
"key4" : "value4"
}' -H 'Content-Type: application/json' -H 'appApiKey : appApiValue' http://[url]:[port]/



URLConnection

public static String method(String urlStr, String requestData) {
  Map<String, Object> response = new HashMap<>();
  ObjectMapper objectMapper = new ObjectMapper();
  
  try {
    URL url = new URL(urlStr);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();

    connection.setRequestMethod(METHOD_TYPE_POST);
    connection.setRequestProperty("User-Agent", USER_AGENT);
    connection.setRequestProperty("Content-Type", "application/json; utf-8");
    connection.setRequestProperty("Accept", "application/json");
    connection.setRequestProperty("appApiKey", SystemPropertyHelper.getProperty("app.api.key"));
    connection.setDoOutput(true); //return값 편집예정일 시

    try(OutputStream os = connection.getOutputStream()) {
      byte[] input = requestData.getBytes("utf-8");
      os.write(input, 0, input.length);
    }

    try(BufferedReader br = new BufferedReader(
        new InputStreamReader(connection.getInputStream(), "utf-8"))) {
      StringBuilder builder = new StringBuilder();
      String responseLine = null;
      while ((responseLine = br.readLine()) != null) {
        builder.append(responseLine.trim());
      }
      log.debug("response = {}", builder.toString());
      response = objectMapper.readValue(builder.toString(), Map.class);
    }
  } catch (Exception e) {
    e.printStackTrace();
  }
  return response.get("data");
}

'개인적 정리' 카테고리의 다른 글

개발 추가 일지  (0) 2023.10.22
네트워크 기본 정리  (0) 2023.10.19
[Linux] 명령어 정리  (0) 2023.08.08
트랜잭션 Isolation levels  (0) 2022.10.14
MEMO 22.10.10  (0) 2022.10.10