Making HTTP Requests in Various Programming Languages
Languages Covered in This Article
This guide provides examples of making HTTP requests in the following programming languages:
- JavaScript
- Node.js
- C++
- Python
- PHP
- Ruby
- Java
- Go
- Android Studio (Java)
- Swift (iOS)
- Perl
- Rust
- Kotlin
Each language offers distinct libraries or tools to perform HTTP requests, which are demonstrated in the following sections.
JavaScript
JavaScript, commonly used in web development, often uses the Fetch API for HTTP requests.
Using Fetch API
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
Node.js
Node.js supports various HTTP libraries. Axios is one of the most popular choices.
Using Axios
const axios = require('axios');
axios.get('https://api.example.com/data')
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error('Error:', error);
});
C++
In C++, you can use the libcurl library to send HTTP requests.
Using libcurl
#include
#include
int main() {
CURL *curl;
CURLcode res;
curl_global_init(CURL_GLOBAL_DEFAULT);
curl = curl_easy_init();
if(curl) {
curl_easy_setopt(curl, CURLOPT_URL, "https://api.example.com/data");
res = curl_easy_perform(curl);
if(res != CURLE_OK)
std::cerr << "curl_easy_perform() failed: " << curl_easy_strerror(res) << std::endl;
curl_easy_cleanup(curl);
}
curl_global_cleanup();
return 0;
}
Python
Python simplifies HTTP requests using the requests library.
Using Requests
import requests
response = requests.get('https://api.example.com/data')
if response.status_code == 200:
data = response.json()
print(data)
else:
print('Error:', response.status_code)
PHP
In PHP, the cURL extension is commonly used to handle HTTP requests.
Using cURL
Ruby
Ruby provides the Net::HTTP library for HTTP requests.
Using Net::HTTP
require 'net/http'
require 'json'
url = URI('https://api.example.com/data')
response = Net::HTTP.get(url)
data = JSON.parse(response)
puts data
Java
Java's HttpURLConnection class is used for making HTTP requests.
Using HttpURLConnection
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpRequestExample {
public static void main(String[] args) {
try {
URL url = new URL("https://api.example.com/data");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
int status = con.getResponseCode();
if (status == 200) {
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuilder content = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
content.append(inputLine);
}
in.close();
System.out.println(content.toString());
} else {
System.out.println("Error: " + status);
}
con.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Go
Go uses the built-in net/http package for HTTP communication.
Using net/http
package main
import (
"fmt"
"io/ioutil"
"net/http"
)
func main() {
resp, err := http.Get("https://api.example.com/data")
if err != nil {
fmt.Println("Error:", err)
return
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusOK {
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Println("Error reading body:", err)
return
}
fmt.Println(string(body))
} else {
fmt.Println("Error: Status Code", resp.StatusCode)
}
}
Android Studio (Java)
In Android, libraries like OkHttp are commonly used to make HTTP requests.
Using OkHttp
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class HttpRequestExample {
public static void main(String[] args) {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("https://api.example.com/data")
.build();
try (Response response = client.newCall(request).execute()) {
if (response.isSuccessful() && response.body() != null) {
System.out.println(response.body().string());
} else {
System.out.println("Error: " + response.code());
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Swift (iOS)
In Swift, you can use the URLSession API to send HTTP requests.
Using URLSession
import Foundation
let url = URL(string: "https://api.example.com/data")!
let task = URLSession.shared.dataTask(with: url) { data, response, error in
if let error = error {
print("Error:", error)
return
}
guard let data = data else {
print("No data")
return
}
if let jsonString = String(data: data, encoding: .utf8) {
print(jsonString)
}
}
task.resume()
Perl
Perl uses the LWP::UserAgent module for making HTTP requests.
Using LWP::UserAgent
use strict;
use warnings;
use LWP::UserAgent;
use JSON;
my $ua = LWP::UserAgent->new;
my $response = $ua->get('https://api.example.com/data');
if ($response->is_success) {
my $data = decode_json($response->decoded_content);
print "$data\n";
} else {
die $response->status_line;
}
Rust
In Rust, the reqwest crate is commonly used for making HTTP requests.
Using reqwest
use reqwest::blocking::get;
use std::error::Error;
fn main() -> Result<(), Box> {
let response = get("https://api.example.com/data")?.text()?;
println!("{}", response);
Ok(())
}
Kotlin
Kotlin often leverages the OkHttp library for network requests.
Using OkHttp
import okhttp3.OkHttpClient
import okhttp3.Request
fun main() {
val client = OkHttpClient()
val request = Request.Builder()
.url("https://api.example.com/data")
.build()
client.newCall(request).execute().use { response ->
if (response.isSuccessful) {
response.body?.string()?.let {
println(it)
}
} else {
println("Error: ${response.code}")
}
}
}
Conclusion
Handling HTTP requests is a core part of programming in modern applications. Whether you're working in Python, JavaScript, Java, or any other language, understanding how to communicate with web services efficiently will significantly improve the quality and capability of your software.