2022년 10월 21일 금요일

[Flutter] 서버에 데이터 보내는 방법과 서버에서 데이터 받는 방법

✌ 안녕하세요.

Flutter는 Http post 방식으로 서버에 API 요청 할 때, 파라미터를 넘기는 방법에 대해 설명 합니다. 

http.post 함수를 사용할 때, body 에, 파라미터를 담아서 보냅니다.

json 형태로 작성하되, jsonEncode() 함수에 담아서 보냅니다.

예시) jsonEncode([{'id':1, 'date':'2022-10-21'}, {'id':1, 'date':'2022-10-21'}])


위 와 같이 Flutter에서 서버에 있는 API를 파라미터를 담아 요청 시, 파라미터가 API에 제대로 전달이 되어야만 합니다.

이때 서버의 API 수신 파라미터 수신객체가 Object 로 받으면, 파라미터의 포맷은 Map 형태가 됩니다.

서버의 언어가 JAVA인 경우, 그리고 Spring boot 에서 API를 만들고, 파라미터를 Object로 받으면, LinkedHashMap 형태로 들어옵니다. 

그러면 Map에서 각 항목을 key값으로 꺼내서, 사용해야합니다.

매번 Map에서  각 항목을 key값으로 꺼내와야 하는 번거로움이 생깁니다.

불편하다면, 다른 방법으로, 수신파라미터 형태를 Object로 받지말고 특정객체로 생성하는 걸로 받으면 됩니다.

예를들어, Searched.java파일을 만들어, 변수로, 수신 받을 key값으로 정의합니다.

그러면, Map 형태 대신, Searched 형태로 받을 수 있습니다.

다른 API함수에 대해서도 같은 Searched.dart 파일을 사용하기 위해, 요청하는 Flutter의 요청 함수에서 사용하는 모든 파라미터 를 Searched.java파일에 넣어놓으면 Searched.java 파일하나로 Flutter의 API 요청을 모두 받아서 처리할 수 있습니다.

😄 감사합니다.



- English -

Flutter describes how to pass parameters when making an API request to the server using the HTTP post method.


When using the http.post function, the body is sent with parameters.


Write it in json format, but send it in the jsonEncode() function.


Example) jsonEncode([{'id':1, 'date':'2022-10-21'}, {'id':1, 'date':'2022-10-21'}])




As above, when Flutter requests an API on the server with parameters, the parameters must be properly passed to the API.


At this time, if the API receiving parameter receiving object of the server receives it as Object, the format of the parameter is in the form of a Map.


When the server language is JAVA, and when you create an API in Spring boot and receive parameters as Objects, they come in the form of LinkedHashMap.


Then, each item from the Map must be retrieved as a key value and used.


It creates a hassle of having to retrieve each item from the Map as a key value every time.


If it is inconvenient, as another method, you can receive the received parameter type by creating it as a specific object instead of receiving it as an Object.


For example, create a Searched.java file and define it as a variable and a key value to receive.


Then, you can receive it in Searched form instead of Map form.


To use the same Searched.dart file for other API functions, put all parameters used in the requesting Flutter request function in the Searched.java file. One Searched.java file can receive and process all Flutter API requests. .

댓글 없음:

댓글 쓰기