Code Examples

Complete code examples for integrating PepeProxy in various programming languages.

Go

Basic HTTP Request

package main

import (
    "fmt"
    "io"
    "net/http"
    "net/url"
)

func main() {
    // Configure proxy
    proxyURL, _ := url.Parse("http://username:password@us-01.pepeproxy.com:2333")

    // Create HTTP client with proxy
    client := &http.Client{
        Transport: &http.Transport{
            Proxy: http.ProxyURL(proxyURL),
        },
    }

    // Make request
    resp, err := client.Get("https://api.ipify.org?format=json")
    if err != nil {
        panic(err)
    }
    defer resp.Body.Close()

    // Read response
    body, _ := io.ReadAll(resp.Body)
    fmt.Println(string(body))
}

With Retry Logic

package main

import (
    "fmt"
    "io"
    "net/http"
    "net/url"
    "time"
)

type ProxyClient struct {
    client *http.Client
}

func NewProxyClient(proxyURL string) *ProxyClient {
    proxy, _ := url.Parse(proxyURL)

    return &ProxyClient{
        client: &http.Client{
            Transport: &http.Transport{
                Proxy: http.ProxyURL(proxy),
            },
            Timeout: 30 * time.Second,
        },
    }
}

func (pc *ProxyClient) GetWithRetry(url string, maxRetries int) (*http.Response, error) {
    var resp *http.Response
    var err error

    for i := 0; i < maxRetries; i++ {
        resp, err = pc.client.Get(url)
        if err == nil && resp.StatusCode == http.StatusOK {
            return resp, nil
        }

        if i < maxRetries-1 {
            waitTime := time.Duration(1<<uint(i)) * time.Second
            fmt.Printf("Retry %d after %v...\n", i+1, waitTime)
            time.Sleep(waitTime)
        }
    }

    return nil, fmt.Errorf("failed after %d retries: %w", maxRetries, err)
}

func main() {
    client := NewProxyClient("http://username:password@us-01.pepeproxy.com:2333")

    resp, err := client.GetWithRetry("https://api.ipify.org?format=json", 3)
    if err != nil {
        panic(err)
    }
    defer resp.Body.Close()

    body, _ := io.ReadAll(resp.Body)
    fmt.Println(string(body))
}

Web Scraping Example

package main

import (
    "fmt"
    "net/http"
    "net/url"
    "strings"

    "github.com/PuerkitoBio/goquery"
)

func scrapeWithProxy(targetURL, proxyURL string) error {
    proxy, _ := url.Parse(proxyURL)

    client := &http.Client{
        Transport: &http.Transport{
            Proxy: http.ProxyURL(proxy),
        },
    }

    req, _ := http.NewRequest("GET", targetURL, nil)
    req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36")

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

    // Parse HTML
    doc, err := goquery.NewDocumentFromReader(resp.Body)
    if err != nil {
        return err
    }

    // Extract data
    doc.Find("h1").Each(func(i int, s *goquery.Selection) {
        fmt.Println("Heading:", strings.TrimSpace(s.Text()))
    })

    return nil
}

func main() {
    err := scrapeWithProxy(
        "https://example.com",
        "http://username:password@us-01.pepeproxy.com:2333",
    )
    if err != nil {
        panic(err)
    }
}

Ruby

Basic HTTP Request

require 'net/http'
require 'uri'

# Configure proxy
proxy_uri = URI.parse('http://us-01.pepeproxy.com:2333')

# Make request through proxy
uri = URI.parse('https://api.ipify.org?format=json')

Net::HTTP.start(
  uri.host,
  uri.port,
  proxy_uri.host,
  proxy_uri.port,
  'username',  # proxy username
  'password',  # proxy password
  use_ssl: uri.scheme == 'https'
) do |http|
  request = Net::HTTP::Get.new(uri)
  request['User-Agent'] = 'Mozilla/5.0'

  response = http.request(request)
  puts response.body
end

Using Rest-Client Gem

require 'rest-client'
require 'json'

# Configure proxy
RestClient.proxy = 'http://username:password@us-01.pepeproxy.com:2333'

# Make request
response = RestClient.get(
  'https://api.ipify.org?format=json',
  {
    user_agent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)',
    timeout: 30
  }
)

data = JSON.parse(response.body)
puts "IP Address: #{data['ip']}"

Web Scraping with Nokogiri

require 'net/http'
require 'uri'
require 'nokogiri'

class ProxyScraper
  def initialize(proxy_url, username, password)
    @proxy_uri = URI.parse(proxy_url)
    @username = username
    @password = password
  end

  def fetch(url)
    uri = URI.parse(url)

    Net::HTTP.start(
      uri.host,
      uri.port,
      @proxy_uri.host,
      @proxy_uri.port,
      @username,
      @password,
      use_ssl: uri.scheme == 'https',
      read_timeout: 30
    ) do |http|
      request = Net::HTTP::Get.new(uri)
      request['User-Agent'] = 'Mozilla/5.0'

      response = http.request(request)

      if response.code.to_i == 200
        parse_html(response.body)
      else
        puts "Error: HTTP #{response.code}"
      end
    end
  rescue StandardError => e
    puts "Error: #{e.message}"
  end

  private

  def parse_html(html)
    doc = Nokogiri::HTML(html)

    # Extract data
    doc.css('h1').each do |heading|
      puts "Heading: #{heading.text.strip}"
    end

    doc.css('.product').each do |product|
      name = product.css('.name').text.strip
      price = product.css('.price').text.strip
      puts "Product: #{name} - #{price}"
    end
  end
end

# Usage
scraper = ProxyScraper.new(
  'http://us-01.pepeproxy.com:2333',
  'username',
  'password'
)

scraper.fetch('https://example.com')

PHP

Basic cURL Request

<?php

$proxy = 'us-01.pepeproxy.com:2333';
$proxyAuth = 'username:password';
$url = 'https://api.ipify.org?format=json';

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_PROXY, $proxy);
curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyAuth);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)');

$response = curl_exec($ch);

if (curl_errno($ch)) {
    echo 'Error: ' . curl_error($ch);
} else {
    $data = json_decode($response, true);
    echo 'IP Address: ' . $data['ip'] . PHP_EOL;
}

curl_close($ch);
?>

With Error Handling

<?php

class ProxyClient {
    private $proxy;
    private $proxyAuth;
    private $timeout;

    public function __construct($proxy, $username, $password, $timeout = 30) {
        $this->proxy = $proxy;
        $this->proxyAuth = "$username:$password";
        $this->timeout = $timeout;
    }

    public function get($url, $headers = []) {
        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_PROXY, $this->proxy);
        curl_setopt($ch, CURLOPT_PROXYUSERPWD, $this->proxyAuth);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, $this->timeout);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);

        if (!empty($headers)) {
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        }

        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $error = curl_error($ch);

        curl_close($ch);

        if ($error) {
            throw new Exception("cURL Error: $error");
        }

        if ($httpCode >= 400) {
            throw new Exception("HTTP Error: $httpCode");
        }

        return $response;
    }

    public function post($url, $data, $headers = []) {
        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_PROXY, $this->proxy);
        curl_setopt($ch, CURLOPT_PROXYUSERPWD, $this->proxyAuth);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, $this->timeout);

        if (!empty($headers)) {
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        }

        $response = curl_exec($ch);
        $error = curl_error($ch);

        curl_close($ch);

        if ($error) {
            throw new Exception("cURL Error: $error");
        }

        return $response;
    }
}

// Usage
try {
    $client = new ProxyClient(
        'us-01.pepeproxy.com:2333',
        'username',
        'password'
    );

    $response = $client->get('https://api.ipify.org?format=json', [
        'User-Agent: Mozilla/5.0',
        'Accept: application/json'
    ]);

    $data = json_decode($response, true);
    echo "IP Address: {$data['ip']}\n";

} catch (Exception $e) {
    echo "Error: {$e->getMessage()}\n";
}
?>

Web Scraping with Simple HTML DOM

<?php
require_once 'simple_html_dom.php';

function scrapeWithProxy($url, $proxy, $username, $password) {
    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_PROXY, $proxy);
    curl_setopt($ch, CURLOPT_PROXYUSERPWD, "$username:$password");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0');

    $html = curl_exec($ch);
    curl_close($ch);

    // Parse HTML
    $dom = str_get_html($html);

    // Extract products
    foreach ($dom->find('.product') as $product) {
        $name = $product->find('.name', 0)->plaintext;
        $price = $product->find('.price', 0)->plaintext;
        echo "Product: $name - $price\n";
    }
}

scrapeWithProxy(
    'https://example.com',
    'us-01.pepeproxy.com:2333',
    'username',
    'password'
);
?>

Java

Basic HTTP Request with HttpClient

import java.net.*;
import java.net.http.*;
import java.time.Duration;
import java.util.Base64;

public class ProxyExample {
    public static void main(String[] args) throws Exception {
        String proxyHost = "us-01.pepeproxy.com";
        int proxyPort = 2333;
        String username = "your_username";
        String password = "your_password";

        // Create proxy
        Proxy proxy = new Proxy(
            Proxy.Type.HTTP,
            new InetSocketAddress(proxyHost, proxyPort)
        );

        // Create HTTP client with proxy
        HttpClient client = HttpClient.newBuilder()
            .proxy(ProxySelector.of(new InetSocketAddress(proxyHost, proxyPort)))
            .connectTimeout(Duration.ofSeconds(30))
            .build();

        // Create request with proxy authentication
        String auth = username + ":" + password;
        String encodedAuth = Base64.getEncoder().encodeToString(auth.getBytes());

        HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create("https://api.ipify.org?format=json"))
            .header("User-Agent", "Mozilla/5.0")
            .header("Proxy-Authorization", "Basic " + encodedAuth)
            .GET()
            .build();

        // Send request
        HttpResponse<String> response = client.send(
            request,
            HttpResponse.BodyHandlers.ofString()
        );

        System.out.println("Response: " + response.body());
    }
}

With Apache HttpClient

import org.apache.http.HttpHost;
import org.apache.http.auth.*;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.*;
import org.apache.http.util.EntityUtils;

public class ProxyScraperApache {
    public static void main(String[] args) {
        String proxyHost = "us-01.pepeproxy.com";
        int proxyPort = 2333;
        String username = "your_username";
        String password = "your_password";

        // Configure proxy
        HttpHost proxy = new HttpHost(proxyHost, proxyPort);

        // Set credentials
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(
            new AuthScope(proxyHost, proxyPort),
            new UsernamePasswordCredentials(username, password)
        );

        // Build client
        CloseableHttpClient httpClient = HttpClients.custom()
            .setDefaultCredentialsProvider(credsProvider)
            .setProxy(proxy)
            .build();

        try {
            // Create request
            HttpGet request = new HttpGet("https://api.ipify.org?format=json");
            request.setHeader("User-Agent", "Mozilla/5.0");

            // Execute request
            CloseableHttpResponse response = httpClient.execute(request);

            try {
                String responseBody = EntityUtils.toString(response.getEntity());
                System.out.println("Response: " + responseBody);
            } finally {
                response.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                httpClient.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

Complete Scraper Class

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.net.*;
import java.io.*;

public class ProxyScraper {
    private String proxyHost;
    private int proxyPort;
    private String username;
    private String password;

    public ProxyScraper(String proxyHost, int proxyPort, String username, String password) {
        this.proxyHost = proxyHost;
        this.proxyPort = proxyPort;
        this.username = username;
        this.password = password;
    }

    public Document fetch(String url) throws IOException {
        // Set up proxy
        Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort));

        // Create authenticator
        Authenticator.setDefault(new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password.toCharArray());
            }
        });

        // Fetch and parse HTML
        Connection connection = Jsoup.connect(url)
            .proxy(proxy)
            .userAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64)")
            .timeout(30000);

        return connection.get();
    }

    public void scrapeProducts(String url) {
        try {
            Document doc = fetch(url);

            // Extract products
            Elements products = doc.select(".product");
            for (Element product : products) {
                String name = product.select(".name").text();
                String price = product.select(".price").text();
                System.out.println("Product: " + name + " - " + price);
            }
        } catch (IOException e) {
            System.err.println("Error scraping: " + e.getMessage());
        }
    }

    public static void main(String[] args) {
        ProxyScraper scraper = new ProxyScraper(
            "us-01.pepeproxy.com",
            8080,
            "username",
            "password"
        );

        scraper.scrapeProducts("https://example.com");
    }
}

C# (.NET)

Basic HTTP Request

using System;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;

class ProxyExample
{
    static async Task Main(string[] args)
    {
        var proxyUri = new Uri("http://us-01.pepeproxy.com:2333");
        var proxy = new WebProxy(proxyUri)
        {
            Credentials = new NetworkCredential("username", "password")
        };

        var handler = new HttpClientHandler
        {
            Proxy = proxy,
            UseProxy = true
        };

        using var client = new HttpClient(handler);
        client.Timeout = TimeSpan.FromSeconds(30);
        client.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0");

        try
        {
            string response = await client.GetStringAsync("https://api.ipify.org?format=json");
            Console.WriteLine($"Response: {response}");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error: {ex.Message}");
        }
    }
}

With Retry Logic

using System;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using Polly;

class ProxyClient
{
    private readonly HttpClient _client;

    public ProxyClient(string proxyUrl, string username, string password)
    {
        var proxy = new WebProxy(proxyUrl)
        {
            Credentials = new NetworkCredential(username, password)
        };

        var handler = new HttpClientHandler
        {
            Proxy = proxy,
            UseProxy = true
        };

        _client = new HttpClient(handler)
        {
            Timeout = TimeSpan.FromSeconds(30)
        };

        _client.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0");
    }

    public async Task<string> GetWithRetryAsync(string url)
    {
        // Define retry policy
        var retryPolicy = Policy
            .Handle<HttpRequestException>()
            .WaitAndRetryAsync(
                retryCount: 3,
                sleepDurationProvider: attempt => TimeSpan.FromSeconds(Math.Pow(2, attempt)),
                onRetry: (exception, timeSpan, retryCount, context) =>
                {
                    Console.WriteLine($"Retry {retryCount} after {timeSpan.TotalSeconds}s");
                }
            );

        return await retryPolicy.ExecuteAsync(async () =>
        {
            var response = await _client.GetAsync(url);
            response.EnsureSuccessStatusCode();
            return await response.Content.ReadAsStringAsync();
        });
    }

    static async Task Main(string[] args)
    {
        var client = new ProxyClient(
            "http://us-01.pepeproxy.com:2333",
            "username",
            "password"
        );

        try
        {
            string result = await client.GetWithRetryAsync("https://api.ipify.org?format=json");
            Console.WriteLine(result);
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Failed: {ex.Message}");
        }
    }
}

Rust

Basic HTTP Request with Reqwest

use reqwest::Proxy;
use std::error::Error;

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    // Configure proxy
    let proxy = Proxy::all("http://username:password@us-01.pepeproxy.com:2333")?;

    // Create client with proxy
    let client = reqwest::Client::builder()
        .proxy(proxy)
        .timeout(std::time::Duration::from_secs(30))
        .build()?;

    // Make request
    let response = client
        .get("https://api.ipify.org?format=json")
        .header("User-Agent", "Mozilla/5.0")
        .send()
        .await?;

    let body = response.text().await?;
    println!("Response: {}", body);

    Ok(())
}

With Error Handling

use reqwest::{Client, Proxy};
use std::time::Duration;

struct ProxyClient {
    client: Client,
}

impl ProxyClient {
    fn new(proxy_url: &str) -> Result<Self, Box<dyn std::error::Error>> {
        let proxy = Proxy::all(proxy_url)?;

        let client = Client::builder()
            .proxy(proxy)
            .timeout(Duration::from_secs(30))
            .build()?;

        Ok(Self { client })
    }

    async fn get_with_retry(
        &self,
        url: &str,
        max_retries: u32,
    ) -> Result<String, Box<dyn std::error::Error>> {
        for attempt in 0..max_retries {
            match self.client.get(url).send().await {
                Ok(response) => {
                    if response.status().is_success() {
                        return Ok(response.text().await?);
                    }
                }
                Err(e) if attempt < max_retries - 1 => {
                    let wait = 2_u64.pow(attempt);
                    println!("Retry {} after {}s...", attempt + 1, wait);
                    tokio::time::sleep(Duration::from_secs(wait)).await;
                    continue;
                }
                Err(e) => return Err(Box::new(e)),
            }
        }

        Err("Max retries exceeded".into())
    }
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = ProxyClient::new("http://username:password@us-01.pepeproxy.com:2333")?;

    match client.get_with_retry("https://api.ipify.org?format=json", 3).await {
        Ok(body) => println!("Success: {}", body),
        Err(e) => eprintln!("Error: {}", e),
    }

    Ok(())
}

Need help with your language? Contact support →