// 需先安装axios:npm install axios
const axios = require('axios');
async function httpRequest() {
const username = 'username';
const password = 'password';
const url = 'https://www.example.com';
try {
// 发起带Basic Auth的GET请求
const response = await axios.get(url, {
auth: {
username: username,
password: password
}
});
// 输出响应内容
console.log('响应内容:', response.data);
} catch (error) {
console.error('请求失败:', error.message);
}
}
// 执行请求
httpRequest();
import okhttp3.Authenticator;
import okhttp3.Credentials;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.Route;
import java.io.IOException;
public class HTTPDemo {
public static void main(String[] args) throws IOException {
// 构建OkHttpClient(带Basic Auth认证)
OkHttpClient client = new OkHttpClient().newBuilder()
.authenticator(new Authenticator() {
@Override
public Request authenticate(Route route, Response response) throws IOException {
// 生成Basic Auth凭证
String credential = Credentials.basic("username", "password");
// 给请求添加Authorization头
return response.request().newBuilder()
.header("Authorization", credential)
.build();
}
})
.build();
// 构建请求
Request request = new Request.Builder()
.url("https://www.example.com")
.build();
// 执行请求并输出响应
Response response = client.newCall(request).execute();
System.out.println(response.body().string());
}
}
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
class HTTPDemo
{
static async Task Main(string[] args)
{
// 初始化HttpClient
using (HttpClient client = new HttpClient())
{
string username = "username";
string password = "password";
string url = "https://www.example.com";
// 设置Basic Auth凭证
var byteArray = System.Text.Encoding.ASCII.GetBytes($"{username}:{password}");
client.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
try
{
// 发起请求并获取响应
HttpResponseMessage response = await client.GetAsync(url);
response.EnsureSuccessStatusCode(); // 抛出HTTP错误
string responseBody = await response.Content.ReadAsStringAsync();
// 输出响应内容
Console.WriteLine(responseBody);
}
catch (HttpRequestException e)
{
Console.WriteLine($"请求失败:{e.Message}");
}
}
}
}
package main
import (
"encoding/base64"
"fmt"
"io/ioutil"
"net/http"
)
func main() {
username := "username"
password := "password"
url := "https://www.example.com"
// 创建HTTP客户端
client := &http.Client{}
// 创建请求
req, err := http.NewRequest("GET", url, nil)
if err != nil {
fmt.Printf("创建请求失败:%v\n", err)
return
}
// 设置Basic Auth凭证
auth := base64.StdEncoding.EncodeToString([]byte(username + ":" + password))
req.Header.Add("Authorization", "Basic "+auth)
// 执行请求
resp, err := client.Do(req)
if err != nil {
fmt.Printf("请求失败:%v\n", err)
return
}
defer resp.Body.Close() // 确保响应体关闭
// 读取响应内容
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Printf("读取响应失败:%v\n", err)
return
}
// 输出响应内容
fmt.Println(string(body))
}
?php
$username = 'username';
$password = 'password';
$url = 'https://www.example.com';
// 初始化cURL
$ch = curl_init($url);
// 设置cURL选项
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // 返回响应内容而非直接输出
curl_setopt($ch, CURLOPT_USERPWD, "$username:$password"); // 设置Basic Auth
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 开发环境可禁用SSL验证(生产环境需开启)
// 执行请求并获取响应
$response = curl_exec($ch);
// 检查错误
if(curl_errno($ch)) {
$error = curl_error($ch);
echo "请求失败:" . $error;
} else {
// 输出响应内容
echo $response;
}
// 关闭cURL
curl_close($ch);
?>
# 需先安装requests:pip install requests
import requests
def http_request():
username = 'username'
password = 'password'
url = 'https://www.example.com'
try:
# 发起带Basic Auth的GET请求
response = requests.get(
url=url,
auth=(username, password) # 自动处理Basic Auth编码
)
response.raise_for_status() # 抛出HTTP错误(4xx/5xx)
# 输出响应内容
print("响应内容:")
print(response.text)
except requests.exceptions.RequestException as e:
print(f"请求失败:{e}")
# 执行请求
if __name__ == "__main__":
http_request()