requests 패키지는 플러터용 라이브러리로, HTTP 요청을 간소화하고 다양한 플랫폼 간에 저장된 쿠키를 관리하도록 설계되었습니다. GET, POST 및 기타 HTTP 메서드를 사용하는 데 직관적인 API를 제공하며, 헤더, 쿼리 매개변수 및 응답 처리를 내장된 지원 기능으로 제공합니다. 자동 쿠키 유지 기능을 포함하여 웹과 유사한 애플리케이션에서 원활한 세션 관리를 가능하게 합니다. Android, iOS, Web, macOS, Windows, Linux와 호환되며, 신뢰할 수 있는 네트워크 통신과 상태 기반 상호작용이 필요한 앱에 적합합니다. 가벼운 설계와 간단한 통합 방식은 반복 코드 없이 효율적인 HTTP 작업을 수행하고자 하는 개발자에게 접근성을 제공합니다.
사용 사례
인증된 API 호출하기
세션 쿠키 처리
REST API 통합 간소화
요청 헤더 및 페이로드 관리
네트워크 엔드포인트 테스트
웹과 유사한 앱 경험 구축
주요 기능
자동 쿠키 저장 및 검색
모든 주요 HTTP 메서드 지원
크로스 플랫폼 호환성
사용하기 쉬운 동기 및 비동기 API
내장된 응답 구문 분석 유틸리티
사용자 지정 가능한 요청 타임아웃
적합한 대상
지속적인 세션을 갖는 앱을 개발하는 개발자
강력한 HTTP 클라이언트 기능을 필요로 하는 앱
일관된 쿠키 관리가 필요한 프로젝트
HTTP 요청에 최소 설정을 원하는 팀
네트워크 기능의 프로토타이핑 또는 빠른 개발
고려 사항
비동기 작업을 신중하게 처리해야 합니다
생산 환경 사용을 위해 추가적인 오류 처리가 필요할 수 있습니다
쿠키 저장 동작은 플랫폼에 따라 달라질 수 있습니다
고성능 및 저지연 시나리오에 적합하지 않습니다
기능이 풍부한 클라이언트에 비해 고급 기능이 제한적입니다
업데이트를 위해 외부 GitHub 저장소에 의존합니다
원본 README
연결된 소스 저장소의 README 원문 스냅샷입니다. 최신 내용은 저장소에서 확인하세요.
a dart library to make HTTP requests (inspired by python requests module). It comes with JSON support and a lightweight implementation to store cookies like a browser.
Cookies, huh?
Server side cookies (via response header SET-COOKIE) are stored using the assistance of quiver.cache. Stored cookies will be send seamlessly on the next http requests you make to the same domain (simple implementation, similar to a web browser).
Install
Add this to your package's pubspec.yaml file:
dependencies:requests:^4.8.0-alpha.0
Usage
Start by importing the library
import'package:requests/requests.dart';
Let's make a simple HTTP request
var r = awaitRequests.get('https://google.com');
r.raiseForStatus();
String body = r.content();
the Response object
just like in python's request module, the Response object has this functionality
r.throwForStatus() - will throw an exception if the response statusCode is not a great success.
r.raiseForStatus() - same as throwForStatus
r.statusCode - the response status code
r.url - the url in the request
r.headers - the response headers
r.success - a boolean. true indicates that the request was a great success
r.hasError - a boolean. true indicates that the request was not a great success
r.bytes() - return the body in the response as a list of bytes
r.content() - return the body in the response as a string
r.json() - recodes the body in the response and returns the result (dynamic type)
Optional Arguments
json - a dynamic object that will be json encoded and then be set as the request's body
body - a raw string to be used as the request's body
bodyEncoding - default RequestBodyEncoding.FormURLEncoded. will set the content-type header
headers - Map<String, String> of custom client headers to add in the request
timeoutSeconds - default 10 seconds. after that period of time without server response an exception is thrown
persistCookies - default true. if should respect server's command to persist cookie
verify - default true. if the SSL verification enabled
withCredentials - default false. for dart web to handle cookies, authorization headers, or TLS client certificates
Note:
Only one optional argument can be used in a single request body or json
Class Methods
.clearStoredCookies(url) - clears the stored cookies for the url
.setStoredCookies(url, CookieJar) - set the stored cookies for the url
.getStoredCookies(url) - returns a CookieJar of the stored cookies for the url
.addCookie(url, name, value) - add a Cookie to the CookieJar associated to the url
Examples
HTTP post, body encoded as application/x-www-form-urlencoded, parse response as json
var r = awaitRequests.delete('https://reqres.in/api/users/10');
r.raiseForStatus();
Ignore SSL self-signed certificate
var r = awaitRequests.get('https://expired.badssl.com/', verify: false);
r.raiseForStatus();
Play with stored cookies
String url = "https://example.com";
awaitRequests.clearStoredCookies(url);
// Set cookies using [CookieJar.parseCookiesString]var cookies = CookieJar.parseCookiesString("name=value");
awaitRequests.setStoredCookies(url, cookies);
// Add single cookie using [CookieJar.parseCookiesString]var cookieJar = awaitRequests.getStoredCookies(url);
cookieJar["name"] = Cookie("name", "value");
awaitRequests.setStoredCookies(url, cookieJar);
// Add a single cookie using [Requests.addCookie]// Same as the above one but without exposing `cookies.dart`Requests.addCookie(url, "name", "value");