Home Backend Development Golang Use the http.Client function to send a customized HTTP request, obtain the response status code and response content, and set the timeout.

Use the http.Client function to send a customized HTTP request, obtain the response status code and response content, and set the timeout.

Jul 24, 2023 pm 03:27 PM
httpclient Get response send request

Use the http.Client function to send customized HTTP requests and obtain the response status code and response content, and set the timeout period

In Go language, we can use net/http package to send HTTP requests and get responses. Among them, you can use the http.Client type to send customized HTTP requests and set the timeout.

Create HTTP client
First, we need to create an object of type http.Client for sending HTTP requests. HTTP transmission related parameters, such as proxy, TLS configuration, etc., can be set by setting the Transport field. By default, the http.DefaultTransport object is used to send requests, and the http.DefaultClient object is used.

The following is a sample code to create an HTTP client:

client := &http.Client{
    Timeout: time.Second * 10,
}
Copy after login

In the above code, we create an HTTP client object client and set the timeout to 10 Second.

Send HTTP request
Use the http.Client object to send an HTTP request. You can use the http.NewRequest function to create a new onehttp.Request object, and then use the Do method of http.Client to send the request and get the response.

The following is an example code for sending an HTTP request:

req, err := http.NewRequest("GET", "https://example.com", nil)
if err != nil {
    log.Fatal(err)
}

resp, err := client.Do(req)
if err != nil {
    log.Fatal(err)
}
defer resp.Body.Close()
Copy after login

In the above code, we create a GET request with the target URL being https://example.com . Then, we use the client.Do(req) method to send the request and get the resp object as a response.

Get the response status code and content
We can use the resp.StatusCode field to get the status code of the HTTP response, use ioutil.ReadAllFunction to read the response content.

The following is a sample code to obtain the response status code and content:

statusCode := resp.StatusCode
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
    log.Fatal(err)
}
Copy after login

In the above code, we use resp.StatusCode to obtain the response status code, use ioutil.ReadAll function to read the response content and store it in the body variable.

Complete example
The following is a complete example that demonstrates how to use http.Client to send a customized HTTP request and obtain the response status code and Content, and set the timeout:

package main

import (
    "fmt"
    "io/ioutil"
    "log"
    "net/http"
    "time"
)

func main() {
    client := &http.Client{
        Timeout: time.Second * 10,
    }

    req, err := http.NewRequest("GET", "https://example.com", nil)
    if err != nil {
        log.Fatal(err)
    }

    resp, err := client.Do(req)
    if err != nil {
        log.Fatal(err)
    }
    defer resp.Body.Close()

    statusCode := resp.StatusCode
    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        log.Fatal(err)
    }

    fmt.Println("Response status code:", statusCode)
    fmt.Println("Response body:", string(body))
}
Copy after login

In the above code, we created an HTTP client object client and set the timeout to 10 seconds. Then, we send a GET request and obtain the response status code and content, and print the output.

By using http.Client to send customized HTTP requests and setting the timeout, we can send HTTP requests more flexibly and process them accordingly based on the status code and content of the response. .

The above is the detailed content of Use the http.Client function to send a customized HTTP request, obtain the response status code and response content, and set the timeout.. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1659
14
PHP Tutorial
1258
29
C# Tutorial
1232
24
Send HTTP request and handle response using HttpClient in Java 11 Send HTTP request and handle response using HttpClient in Java 11 Aug 01, 2023 am 11:48 AM

Title: Sending HTTP requests and handling responses using HttpClient in Java11 Introduction: In modern Internet applications, HTTP communication with other servers is a very common task. Java provides some built-in tools that can help us achieve this goal. The latest and recommended one is the HttpClient class introduced in Java11. This article will introduce how to use HttpClient in Java11 to send HTTP requests and process responses,

How to use http.Client in golang for advanced operations of HTTP requests How to use http.Client in golang for advanced operations of HTTP requests Nov 18, 2023 am 11:37 AM

How to use http.Client in golang for advanced operations of HTTP requests Introduction: In modern development, HTTP requests are an inevitable part. Golang provides a powerful standard library, which includes the http package. The http package provides the http.Client structure for sending HTTP requests and receiving HTTP responses. In this article, we will explore how to use http.Client to perform advanced operations on HTTP requests and provide specific code examples.

How to compare redirection and request forwarding using httpclient in Java How to compare redirection and request forwarding using httpclient in Java Apr 21, 2023 pm 11:43 PM

Here is an introduction: In HttpClient4.x version, the get request method will automatically redirect, but the post request method will not automatically redirect. This is something to pay attention to. The last time I made an error was when I used post to submit the form to log in, and there was no automatic redirection at that time. The difference between request forwarding and redirection 1. Redirection is two requests, and forwarding is one request, so the forwarding speed is faster than redirection. 2. After redirection, the address on the address bar will change to the address requested for the second time. After forwarding, the address on the address bar will not change and remains the address requested for the first time. 3. Forwarding is a server behavior, and redirection is a client behavior. When redirecting, the URL on the browser changes; when forwarding, the URL on the browser remains unchanged.

How to send HTTP request using Java HttpClient How to send HTTP request using Java HttpClient Apr 20, 2023 pm 11:49 PM

1. Import the dependency org.apache.httpcomponentshttpclient4.5.3com.alibabafastjson1.2.58org.apache.httpcomponentshttpmime4.5.3org.apache.httpcomponentshttpcore4.4.13org.slf4jslf4j-api1.7.72. Use the tool class. This tool class converts get requests and post requests. Several parameter passing methods have been written, including get address bar passing parameters, get params passing parameters, post params passing parameters, post

Use the http.Get function to send a GET request and get the response Use the http.Get function to send a GET request and get the response Jul 24, 2023 pm 12:49 PM

Use the http.Get function to send a GET request and get the response. In network programming, sending HTTP requests is a very common operation. By sending HTTP requests, we can obtain data on the remote server or interact with it. In the Go language, we can use the http package to send HTTP requests and use the http.Get function to send GET requests and get responses. The http.Get function is a simple function provided in the http package. It is used to send a GET request and return a

Send asynchronous HTTP requests and handle responses using the new HttpClient in Java 11 Send asynchronous HTTP requests and handle responses using the new HttpClient in Java 11 Jul 31, 2023 pm 02:24 PM

Send asynchronous HTTP requests and process responses using the new HttpClient in Java 11 In Java 11, the new HttpClient class was introduced, providing powerful functionality to send HTTP requests and process responses. Compared with the previous HttpURLConnection, the new HttpClient is easier to use and supports asynchronous operations, making it more efficient to handle concurrent requests. This article will introduce how to use the new HttpCli in Java11

Detailed explanation of Python HTTP requests: sending, receiving and parsing network requests Detailed explanation of Python HTTP requests: sending, receiving and parsing network requests Feb 24, 2024 pm 03:10 PM

In today's online world, Http requests have become an essential technology, which allows us to communicate with the server, obtain data and perform various operations. As a powerful programming language, python provides a wealth of libraries and tools to make HTTP requests easier to implement. It is crucial for developers to understand and master the principles and implementation methods of HTTP requests. In this article, we will explain in detail the basic process of Python HTTP requests, including sending requests, receiving responses, and parsing responses. At the same time, we will provide demonstration code to help you quickly master the implementation method of HTTP requests. Sending an HTTP request First, you need to create a requests.Session()

Analysis of error handling examples of HttpClient in Java Analysis of error handling examples of HttpClient in Java May 08, 2023 am 11:07 AM

Note 1. HttpClient asynchronous request returns CompletableFuture, and its own exceptionally method can be used for fallback processing. 2. Unlike WebClient, HttpClient does not have 4xx or 5xx status code exceptions. You need to handle it according to your own situation, manually detect status code exceptions or return other content. Example@TestpublicvoidtestHandleException()throwsExecutionException,InterruptedException{HttpClientclient=Ht

See all articles