티스토리 뷰

반응형

✅ 1. 사용 준비

Laravel 7부터 기본 제공되며, Laravel 12에도 포함되어 있습니다.

use Illuminate\Support\Facades\Http;

✅ 2. GET 요청

$response = Http::get('https://jsonplaceholder.typicode.com/posts/1');

$data = $response->json(); // 배열로 반환
dd($data);

✅ 3. POST 요청

$response = Http::post('https://httpbin.org/post', [
    'name' => 'John Doe',
    'email' => 'john@example.com',
]);

dd($response->json());

✅ 4. 헤더 포함 요청

$response = Http::withHeaders([
    'Authorization' => 'Bearer your-token',
])->get('https://api.example.com/user');

dd($response->json());

✅ 5. 쿼리스트링 포함 GET 요청

$response = Http::get('https://api.example.com/search', [
    'query' => 'Laravel',
    'page' => 2,
]);

dd($response->json());

✅ 6. JSON 응답 처리

if ($response->successful()) {
    $data = $response->json();
    // 데이터 처리
} elseif ($response->failed()) {
    // 에러 처리
}

✅ 7. 예외 처리 + 타임아웃

use Illuminate\Http\Client\RequestException;

try {
    $response = Http::timeout(5)->get('https://slow.api.com');
    $data = $response->json();
} catch (RequestException $e) {
    // 예외 처리
    logger()->error('API 호출 실패: ' . $e->getMessage());
}

✅ 8. 파일 업로드 (멀티파트)

$response = Http::attach(
    'file', file_get_contents(storage_path('app/sample.txt')), 'sample.txt'
)->post('https://api.example.com/upload');

dd($response->json());

✅ 9. 기본 설정 적용 (서비스 프로바이더에서)

Http::macro('myApi', function () {
    return Http::withHeaders([
        'Authorization' => 'Bearer your-token',
    ])->baseUrl('https://api.example.com');
});

// 사용
$response = Http::myApi()->get('/users');

✅ 10. 테스트에서 Fake 사용

Http::fake([
    'https://api.example.com/*' => Http::response(['id' => 1, 'name' => 'Fake User'], 200),
]);

$response = Http::get('https://api.example.com/user');
dd($response->json());

🔚 요약

  • Http::get/post/put/delete() 로 다양한 HTTP 요청 가능
  • withHeaders(), timeout(), attach() 등 다양한 옵션 지원
  • json(), successful(), status() 등으로 응답 처리 용이
  • Http::fake() 로 테스트도 간편하게 작성 가능
반응형

'배움 > PHP' 카테고리의 다른 글

ReflectionClass ?  (0) 2025.07.04
ob_get_contents  (0) 2025.07.03
Laravel Helper Class 사용법  (0) 2025.07.01
프록시 설정, User-Agent 설정 등  (0) 2025.06.24
parallel 웹 크롤러  (0) 2025.06.24
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/08   »
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31
글 보관함