새 함수를 만드는 경우 Cloud Run의
콘솔 빠른 시작을 참고하세요.
HTTP 요청 전송
컬렉션을 사용해 정리하기
내 환경설정을 기준으로 콘텐츠를 저장하고 분류하세요.
Cloud 함수에서 HTTP 요청 전송 방법을 보여줍니다.
코드 샘플
C#
Cloud Run Functions에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다.
자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.
Go
Cloud Run Functions에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다.
자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.
Java
Cloud Run Functions에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다.
자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.
Node.js
Cloud Run Functions에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다.
자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.
PHP
Cloud Run Functions에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다.
자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.
Python
Cloud Run Functions에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다.
자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.
Ruby
Cloud Run Functions에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다.
자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.
달리 명시되지 않는 한 이 페이지의 콘텐츠에는 Creative Commons Attribution 4.0 라이선스에 따라 라이선스가 부여되며, 코드 샘플에는 Apache 2.0 라이선스에 따라 라이선스가 부여됩니다. 자세한 내용은 Google Developers 사이트 정책을 참조하세요. 자바는 Oracle 및/또는 Oracle 계열사의 등록 상표입니다.
[[["이해하기 쉬움","easyToUnderstand","thumb-up"],["문제가 해결됨","solvedMyProblem","thumb-up"],["기타","otherUp","thumb-up"]],[["이해하기 어려움","hardToUnderstand","thumb-down"],["잘못된 정보 또는 샘플 코드","incorrectInformationOrSampleCode","thumb-down"],["필요한 정보/샘플이 없음","missingTheInformationSamplesINeed","thumb-down"],["번역 문제","translationIssue","thumb-down"],["기타","otherDown","thumb-down"]],[],[[["\u003cp\u003eThis page demonstrates how to make an HTTP request from a Cloud Function using various programming languages.\u003c/p\u003e\n"],["\u003cp\u003eCode examples are provided in C#, Go, Java, Node.js, PHP, Python, and Ruby, each showcasing a method for making an external HTTP request.\u003c/p\u003e\n"],["\u003cp\u003eThe examples highlight the use of HTTP client libraries within Cloud Functions to interact with external URLs, such as fetching content from "http://example.com" or "https://example.com".\u003c/p\u003e\n"],["\u003cp\u003eAuthentication to Cloud Run functions is emphasized, recommending the setup of Application Default Credentials for secure local development environments, with a link provided for more information.\u003c/p\u003e\n"]]],[],null,["Shows how to make an HTTP request from a Cloud Function.\n\nCode sample \n\nC#\n\n\nTo authenticate to Cloud Run functions, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n using Google.Cloud.Functions.Framework;\n using Google.Cloud.Functions.Hosting;\n using Microsoft.AspNetCore.Hosting;\n using Microsoft.AspNetCore.Http;\n using https://cloud.google.com/dotnet/docs/reference/Google.Cloud.Memorystore.V1Beta/latest/Microsoft.Extensions.DependencyInjection.html;\n using System.Net.Http;\n using System.Threading.Tasks;\n\n namespace SendHttpRequest;\n\n // Dependency injection configuration, executed during server startup.\n public class Startup : FunctionsStartup\n {\n public override void ConfigureServices(WebHostBuilderContext context, IServiceCollection services)\n {\n // Make an HttpClient available to our function via dependency injection.\n // There are many options here; see\n // https://docs.microsoft.com/en-us/aspnet/core/fundamentals/http-requests\n // for more details.\n services.AddHttpClient\u003cIHttpFunction, Function\u003e();\n }\n }\n\n // Function, decorated with the FunctionsStartup attribute to specify the startup class\n // for dependency injection.\n [FunctionsStartup(typeof(Startup))]\n public class Function : IHttpFunction\n {\n private readonly HttpClient _httpClient;\n\n public Function(HttpClient httpClient) =\u003e\n _httpClient = httpClient;\n\n public async Task HandleAsync(HttpContext context)\n {\n string url = \"http://example.com\";\n using (HttpResponseMessage clientResponse = await _httpClient.GetAsync(url, context.RequestAborted))\n {\n await context.Response.WriteAsync(\n $\"Received code '{(int) clientResponse.StatusCode}' from URL '{url}'.\",\n context.RequestAborted);\n }\n }\n }\n\nGo\n\n\nTo authenticate to Cloud Run functions, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n\n // Package http provides a set of HTTP Cloud Functions samples.\n package http\n\n import (\n \t\"fmt\"\n \t\"net/http\"\n \t\"time\"\n\n \t\"github.com/GoogleCloudPlatform/functions-framework-go/functions\"\n )\n\n var urlString = \"https://example.com\"\n\n // client is used to make HTTP requests with a 10 second timeout.\n // http.Clients should be reused instead of created as needed.\n var client = &http.Client{\n \tTimeout: 10 * time.Second,\n }\n\n func init() {\n \tfunctions.HTTP(\"MakeRequest\", MakeRequest)\n }\n\n // MakeRequest is an example of making an HTTP request. MakeRequest uses a\n // single http.Client for all requests to take advantage of connection\n // pooling and caching. See https://godoc.org/net/http#Client.\n func MakeRequest(w http.ResponseWriter, r *http.Request) {\n \tresp, err := client.Get(urlString)\n \tif err != nil {\n \t\thttp.Error(w, \"Error making request\", http.StatusInternalServerError)\n \t\treturn\n \t}\n \tif resp.StatusCode != http.StatusOK {\n \t\tmsg := fmt.Sprintf(\"Bad StatusCode: %d\", resp.StatusCode)\n \t\thttp.Error(w, msg, http.StatusInternalServerError)\n \t\treturn\n \t}\n \tfmt.Fprintf(w, \"ok\")\n }\n\nJava\n\n\nTo authenticate to Cloud Run functions, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n\n import com.google.cloud.functions.HttpFunction;\n import com.google.cloud.functions.HttpRequest;\n import com.google.cloud.functions.HttpResponse;\n import java.io.IOException;\n import java.io.PrintWriter;\n import java.net.URI;\n import java.net.http.HttpClient;\n import java.net.http.HttpResponse.BodyHandlers;\n import java.time.Duration;\n\n public class SendHttpRequest implements HttpFunction {\n\n // Create a client with some reasonable defaults. This client can be reused for multiple requests.\n // (java.net.httpClient also pools connections automatically by default.)\n private static HttpClient client =\n HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(10)).build();\n\n @Override\n public void service(HttpRequest request, HttpResponse response)\n throws IOException, InterruptedException {\n // Create a GET sendHttpRequest to \"http://example.com\"\n String url = \"http://example.com\";\n var getRequest = java.net.http.HttpRequest.newBuilder().uri(URI.create(url)).GET().build();\n\n // Send the sendHttpRequest using the client\n var getResponse = client.send(getRequest, BodyHandlers.ofString());\n\n // Write the results to the output:\n var writer = new PrintWriter(response.getWriter());\n writer.printf(\"Received code '%s' from url '%s'.\", getResponse.statusCode(), url);\n }\n }\n\nNode.js\n\n\nTo authenticate to Cloud Run functions, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n const fetch = require('node-fetch');\n const functions = require('@google-cloud/functions-framework');\n\n /**\n * HTTP Cloud Function that makes an HTTP request\n *\n * @param {Object} req Cloud Function request context.\n * @param {Object} res Cloud Function response context.\n */\n functions.http('makeRequest', async (req, res) =\u003e {\n const url = 'https://example.com'; // URL to send the request to\n const externalRes = await fetch(url);\n res.sendStatus(externalRes.ok ? 200 : 500);\n });\n\nPHP\n\n\nTo authenticate to Cloud Run functions, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n\n use Psr\\Http\\Message\\ServerRequestInterface;\n use Psr\\Http\\Message\\ResponseInterface;\n use GuzzleHttp\\Client;\n use GuzzleHttp\\Psr7\\Response;\n\n function makeRequest(ServerRequestInterface $request): ResponseInterface\n {\n // This sample uses the GuzzleHTTP client\n // See its documentation for usage information\n // https://docs.guzzlephp.org/en/stable/\n\n // Specify the URL to send requests to\n $client = new Client([\n 'base_uri' =\u003e 'https://example.com',\n ]);\n\n // Send the request\n $url_response = $client-\u003eget('/');\n\n $function_response = new Response(\n $url_response-\u003egetStatusCode(),\n [], // headers\n '' // body\n );\n\n return $function_response;\n }\n\nPython\n\n\nTo authenticate to Cloud Run functions, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n import functions_framework\n\n\n @functions_framework.http\n def make_request(request):\n \"\"\"\n HTTP Cloud Function that makes another HTTP request.\n Args:\n request (flask.Request): The request object.\n \u003chttp://flask.pocoo.org/docs/1.0/api/#flask.Request\u003e\n Returns:\n The response text, or any set of values that can be turned into a\n Response object using `make_response`\n \u003chttp://flask.pocoo.org/docs/1.0/api/#flask.Flask.make_response\u003e.\n \"\"\"\n import requests\n\n # The URL to send the request to\n url = \"http://example.com\"\n\n # Process the request\n response = requests.get(url)\n response.raise_for_status()\n return \"Success!\"\n\nRuby\n\n\nTo authenticate to Cloud Run functions, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n require \"functions_framework\"\n require \"net/http\"\n\n FunctionsFramework.http \"concepts_requests\" do |_request|\n url = \"example.com\"\n response = Net::HTTP.get_response url, \"/\"\n \"Received code: #{response.code} from url: #{url}\"\n end\n\nWhat's next\n\n\nTo search and filter code samples for other Google Cloud products, see the\n[Google Cloud sample browser](/docs/samples?product=functions)."]]