b title: api接口代码样例

本文档包含调用快代理api的代码样例,供开发者参考。

代码样例使用说明

  1. 代码样例直接运行无法得到正确的结果,因为代码中的api链接是虚构的,您替换成自己真实的链接就可以正常运行了。
    生成api链接:      
  2. 代码样例正常运行所需的运行环境和注意事项在样例末尾均有说明,使用前请仔细阅读。
  3. 使用代码样例过程中遇到问题请,我们会为您提供尊龙现金一下的技术支持。

python

requests

requests (python2/3)

使用提示

  • 此样例支持 python 2.6—2.7以及3.3—3.7
  • 不是python原生库,需要安装才能使用: pip install requests
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""使用requests请求代理服务器
请求http和https网页均适用
"""
import requests
import random
page_url = "http://dev.kdlapi.com/testproxy"  # 要访问的目标网页
# api接口,返回格式为json
api_url = "http://dps.kdlapi.com/api/getdps?orderid=96518362xxxxxx&num=10&format=json&sep=1"
# api接口返回的ip
proxy_ip = requests.get(api_url).json()['data']['proxy_list']
# 用户名密码认证(私密代理/独享代理)
username = "username"
password = "password"
proxies = {
    "http": "http://%(user)s:%(pwd)s@%(proxy)s/" % {'user': username, 'pwd': password, 'proxy': random.choice(proxy_ip)},
    "https": "https://%(user)s:%(pwd)s@%(proxy)s/" % {'user': username, 'pwd': password, 'proxy': random.choice(proxy_ip)}
}
headers = {
    "accept-encoding": "gzip",  # 使用gzip压缩传输数据让访问更快
}
r = requests.get(page_url, proxies=proxies, headers=headers)
print(r.status_code)  # 获取response的返回码
if r.status_code == 200:
    r.enconding = "utf-8"  # 设置返回内容的编码
    print(r.content)  # 获取页面内容

urllib2

urllib2 (python2)

使用提示

  • 运行环境要求 python2.6 / 2.7
#!/usr/bin/env python
#-*- coding: utf-8 -*-
"""使用urllib2调用api接口
"""
import urllib2
import zlib
#api链接
api_url = "http://dev.kdlapi.com/api/getproxy/?orderid=96518362xxxxxx&num=100&protocol=1&method=2&an_ha=1&sep=1"
req = urllib2.request(api_url)
req.add_header("accept-encoding", "gzip") #使用gzip压缩传输数据让访问更快
r = urllib2.urlopen(req)
print r.code #获取reponse的返回码
content_encoding = r.headers.getheader("content-encoding")
if content_encoding and "gzip" in content_encoding:
    print zlib.decompress(r.read(), 16zlib.max_wbits) #获取页面内容
else:
    print r.read() #获取页面内容

urllib

urllib (python3)

使用提示

  • 运行环境要求 python3.x
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""使用urllib.request调用api接口(在python3中urllib2被改为urllib.request)
"""
import urllib.request
import zlib
#api链接
api_url = "http://dev.kdlapi.com/api/getproxy/?orderid=96518362xxxxxx&num=100&protocol=1&method=2&an_ha=1&sep=1"
headers = {"accept-encoding": "gzip"}  #使用gzip压缩传输数据让访问更快
req = urllib.request.request(url=api_url, headers=headers)
# 请求api链接
res = urllib.request.urlopen(req) 
print(res.code)  # 获取reponse的返回码
content_encoding = res.headers.get('content-encoding')
if content_encoding and "gzip" in content_encoding:
    print(zlib.decompress(res.read(), 16  zlib.max_wbits).decode('utf-8'))  #获取页面内容
else:
    print(res.read().decode('utf-8'))  #获取页面内容

java

jdk

使用原生库

使用提示

运行环境要求 jdk >= 1.6

package com.kuaidaili.sdk;
/**
 * 使用jdk原生库调用api
 */
public class testapi {
    private static string apiurl = "http://dev.kdlapi.com/api/getproxy?orderid=96518362xxxxxx&num=10&format=json&sep=1"; //api链接
    public static void main(string[] args) {
        httprequest request = new httprequest();
        map<string, string> headers = new hashmap<string, string>();
        headers.put("accept-encoding", "gzip"); //使用gzip压缩传输数据让访问更快
        try{
            httpresponse response = request.sendget(apiurl, null, headers, null);
            system.out.println(response.getcode());
            system.out.println(response.getcontent());
        }
        catch (exception e) {
            e.printstacktrace();
        }
    }
}
查看工具类httprequest和httpresponse

httprequest.java

package com.kuaidaili.sdk;
import java.io.bufferedreader;
import java.io.bytearrayinputstream;
import java.io.bytearrayoutputstream;
import java.io.ioexception;
import java.io.inputstream;
import java.io.inputstreamreader;
import java.net.authenticator;
import java.net.httpurlconnection;
import java.net.inetsocketaddress;
import java.net.passwordauthentication;
import java.net.proxy;
import java.net.url;
import java.net.urlencoder;
import java.nio.charset.charset;
import java.util.map;
import java.util.vector;
import java.util.zip.gzipinputstream;
/**
 * http请求对象
 */
public class httprequest {
    private string defaultcontentencoding;
    private int connecttimeout = 1000;
    private int readtimeout = 1000;
    public httprequest() {
        this.defaultcontentencoding = charset.defaultcharset().name();
    }
    /**
     * 发送get请求
     *
     * @param urlstring url地址
     * @param proxysettings 代理设置,null代表不设置代理
     * @return 响应对象
     */
    public httpresponse sendget(string urlstring, final map<string, string> proxysettings) throws ioexception {
        return this.send(urlstring, "get", null, null, proxysettings);
    }
    /**
     * 发送get请求
     *
     * @param urlstring url地址
     * @param params 参数集合
     * @param proxysettings 代理设置,null代表不设置代理
     * @return 响应对象
     */
    public httpresponse sendget(string urlstring, map<string, string> params, final map<string, string> proxysettings)
            throws ioexception {
        return this.send(urlstring, "get", params, null, proxysettings);
    }
    /**
     * 发送get请求
     *
     * @param urlstring url地址
     * @param params 参数集合
     * @param headers header集合
     * @param proxysettings 代理设置,null代表不设置代理
     * @return 响应对象
     */
    public httpresponse sendget(string urlstring, map<string, string> params,
            map<string, string> headers, final map<string, string> proxysettings) throws ioexception {
        return this.send(urlstring, "get", params, headers, proxysettings);
    }
    /**
     * 发送post请求
     *
     * @param urlstring url地址
     * @param proxysettings 代理设置,null代表不设置代理
     * @return 响应对象
     */
    public httpresponse sendpost(string urlstring, final map<string, string> proxysettings) throws ioexception {
        return this.send(urlstring, "post", null, null, proxysettings);
    }
    /**
     * 发送post请求
     *
     * @param urlstring url地址
     * @param params 参数集合
     * @param proxysettings 代理设置,null代表不设置代理
     * @return 响应对象
     */
    public httpresponse sendpost(string urlstring, map<string, string> params, final map<string, string> proxysettings)
            throws ioexception {
        return this.send(urlstring, "post", params, null, proxysettings);
    }
    /**
     * 发送post请求
     *
     * @param urlstring url地址
     * @param params 参数集合
     * @param headers header集合
     * @param proxysettings 代理设置,null代表不设置代理
     * @return 响应对象
     */
    public httpresponse sendpost(string urlstring, map<string, string> params,
            map<string, string> headers, final map<string, string> proxysettings) throws ioexception {
        return this.send(urlstring, "post", params, headers, proxysettings);
    }
    /**
     * 发送http请求
     */
    private httpresponse send(string urlstring, string method,
            map<string, string> parameters, map<string, string> headers, final map<string, string> proxysettings)
            throws ioexception {
        httpurlconnection urlconnection = null;
        if (method.equalsignorecase("get") && parameters != null) {
            stringbuffer param = new stringbuffer();
            int i = 0;
            for (string key : parameters.keyset()) {
                if (i == 0)
                    param.append("?");
                else
                    param.append("&");
                param.append(key).append("=").append(urlencoder.encode(parameters.get(key), "utf-8"));
                i  ;
            }
            urlstring  = param;
        }
        url url = new url(urlstring);
        if(proxysettings != null){
            proxy proxy = new proxy(proxy.type.http, new inetsocketaddress(proxysettings.get("ip"), integer.parseint(proxysettings.get("port"))));
            urlconnection = (httpurlconnection) url.openconnection(proxy);
            if(proxysettings.containskey("username")){
                authenticator authenticator = new authenticator() {
                    public passwordauthentication getpasswordauthentication() {
                        return (new passwordauthentication(proxysettings.get("username"),
                                proxysettings.get("password").tochararray()));
                    }
                };
                authenticator.setdefault(authenticator);
            }
        }
        else{
            urlconnection = (httpurlconnection) url.openconnection();
        }
        urlconnection.setrequestmethod(method);
        urlconnection.setdooutput(true);
        urlconnection.setdoinput(true);
        urlconnection.setusecaches(false);
        urlconnection.setconnecttimeout(connecttimeout);
        urlconnection.setreadtimeout(readtimeout);
        if (headers != null)
            for (string key : headers.keyset()) {
                urlconnection.addrequestproperty(key, headers.get(key));
            }
        if (method.equalsignorecase("post") && parameters != null) {
            stringbuffer param = new stringbuffer();
            int i = 0;
            for (string key : parameters.keyset()) {
                if(i > 0) param.append("&");
                param.append(key).append("=").append(urlencoder.encode(parameters.get(key), "utf-8"));
                i  ;
            }
            system.out.println(param.tostring());
            urlconnection.getoutputstream().write(param.tostring().getbytes());
            urlconnection.getoutputstream().flush();
            urlconnection.getoutputstream().close();
        }
        return this.makecontent(urlstring, urlconnection);
    }
    /**
     * 得到响应对象
     */
    private httpresponse makecontent(string urlstring,
            httpurlconnection urlconnection) throws ioexception {
        httpresponse response = new httpresponse();
        try {
            inputstream in = urlconnection.getinputstream();
            bufferedreader bufferedreader = new bufferedreader(new inputstreamreader(in));
            if ("gzip".equals(urlconnection.getcontentencoding())) bufferedreader =  new bufferedreader(new inputstreamreader(new gzipinputstream(in)));
            response.contentcollection = new vector<string>();
            stringbuffer temp = new stringbuffer();
            string line = bufferedreader.readline();
            while (line != null) {
                response.contentcollection.add(line);
                temp.append(line).append("\r\n");
                line = bufferedreader.readline();
            }
            bufferedreader.close();
            string encoding = urlconnection.getcontentencoding();
            if (encoding == null)
                encoding = this.defaultcontentencoding;
            response.urlstring = urlstring;
            response.defaultport = urlconnection.geturl().getdefaultport();
            response.file = urlconnection.geturl().getfile();
            response.host = urlconnection.geturl().gethost();
            response.path = urlconnection.geturl().getpath();
            response.port = urlconnection.geturl().getport();
            response.protocol = urlconnection.geturl().getprotocol();
            response.query = urlconnection.geturl().getquery();
            response.ref = urlconnection.geturl().getref();
            response.userinfo = urlconnection.geturl().getuserinfo();
            response.contentlength = urlconnection.getcontentlength();
            response.content = new string(temp.tostring().getbytes());
            response.contentencoding = encoding;
            response.code = urlconnection.getresponsecode();
            response.message = urlconnection.getresponsemessage();
            response.contenttype = urlconnection.getcontenttype();
            response.method = urlconnection.getrequestmethod();
            response.connecttimeout = urlconnection.getconnecttimeout();
            response.readtimeout = urlconnection.getreadtimeout();
            return response;
        } catch (ioexception e) {
            throw e;
        } finally {
            if (urlconnection != null){
                urlconnection.disconnect();
            }
        }
    }
    public static byte[] gunzip(byte[] bytes) {  
        if (bytes == null || bytes.length == 0) {  
            return null;  
        }  
        bytearrayoutputstream out = new bytearrayoutputstream();  
        bytearrayinputstream in = new bytearrayinputstream(bytes);  
        try {  
            gzipinputstream ungzip = new gzipinputstream(in);  
            byte[] buffer = new byte[256];  
            int n;  
            while ((n = ungzip.read(buffer)) >= 0) {  
                out.write(buffer, 0, n);  
            }  
        } catch (ioexception e) {  
            system.err.println("gzip uncompress error.");
            e.printstacktrace();
        }  
        return out.tobytearray();  
    }
    /**
     * 得到默认的响应字符集
     */
    public string getdefaultcontentencoding() {
        return this.defaultcontentencoding;
    }
    /**
     * 设置默认的响应字符集
     */
    public void setdefaultcontentencoding(string defaultcontentencoding) {
        this.defaultcontentencoding = defaultcontentencoding;
    }
    public int getconnecttimeout() {
        return connecttimeout;
    }
    public void setconnecttimeout(int connecttimeout) {
        this.connecttimeout = connecttimeout;
    }
    public int getreadtimeout() {
        return readtimeout;
    }
    public void setreadtimeout(int readtimeout) {
        this.readtimeout = readtimeout;
    }
}

httpresponse.java

package com.kuaidaili.sdk;
import java.util.vector;
/**
 * http响应对象
 */
public class httpresponse {
    string urlstring;
    int defaultport;
    string file;
    string host;
    string path;
    int port;
    string protocol;
    string query;
    string ref;
    string userinfo;
    string contentencoding;
    int contentlength;
    string content;
    string contenttype;
    int code;
    string message;
    string method;
    int connecttimeout;
    int readtimeout;
    vector<string> contentcollection;
    public string getcontent() {
        return content;
    }
    public string getcontenttype() {
        return contenttype;
    }
    public int getcode() {
        return code;
    }
    public string getmessage() {
        return message;
    }
    public vector<string> getcontentcollection() {
        return contentcollection;
    }
    public string getcontentencoding() {
        return contentencoding;
    }
    public string getmethod() {
        return method;
    }
    public int getconnecttimeout() {
        return connecttimeout;
    }
    public int getreadtimeout() {
        return readtimeout;
    }
    public string geturlstring() {
        return urlstring;
    }
    public int getdefaultport() {
        return defaultport;
    }
    public string getfile() {
        return file;
    }
    public string gethost() {
        return host;
    }
    public string getpath() {
        return path;
    }
    public int getport() {
        return port;
    }
    public string getprotocol() {
        return protocol;
    }
    public string getquery() {
        return query;
    }
    public string getref() {
        return ref;
    }
    public string getuserinfo() {
        return userinfo;
    }
}

httpclient

httpclient-4.5.6

使用提示

  1. 此样例同时支持访问http和https网页
  2. 运行环境要求 jdk >= 1.6
  3. 依赖包:
    httpclient-4.5.6.jar()
    httpcore-4.4.10.jar()
    commons-codec-1.10.jar()
    commons-logging-1.2.jar()
package com.kuaidaili.sdk;
import org.apache.http.client.methods.closeablehttpresponse;
import org.apache.http.client.methods.httpget;
import org.apache.http.impl.client.closeablehttpclient;
import org.apache.http.impl.client.httpclients;
import org.apache.http.util.entityutils;
/**
 * 使用httpclient调用api接口
 */
public class testapihttpclient {
    private static string apiurl = "http://dev.kdlapi.com/api/getproxy/?orderid=96518362xxxxxx&num=100&protocol=1&method=2&an_ha=1&sep=1"; //api链接
    public static void main(string[] args) throws exception {
        closeablehttpclient httpclient = httpclients.createdefault();
        try {
            httpget httpget = new httpget(apiurl);
            httpget.addheader("accept-encoding", "gzip"); //使用gzip压缩传输数据让访问更快
            system.out.println("executing request "  httpget.geturi());
            closeablehttpresponse response = httpclient.execute(httpget);
            try {
                system.out.println(response.getstatusline()); //获取reponse的返回码
                system.out.println(entityutils.tostring(response.getentity())); //获取api返回内容
            } finally {
                response.close();
            }
        } finally {
            httpclient.close();
        }
    }
}

golang

标准库
package main
//go版本 go1
import (
    "compress/gzip"
    "fmt"
    "io"
    "io/ioutil"
    "net/http"
    "os"
)
func main() {
    // api链接
    api_url := "http://svip.kdlapi.com/api/getproxy/?orderid=96518362xxxxxx&num=100&protocol=1&method=2&an_an=1&an_ha=1&sep=1"
    // 请求api链接
    req, _ := http.newrequest("get", api_url, nil)
    req.header.add("accept-encoding", "gzip") //使用gzip压缩传输数据让访问更快
    client := &http.client{}
    res, err := client.do(req)
    // 处理返回结果
    if err != nil {
        // 请求发生异常
        fmt.println(err.error())
    } else {
        defer res.body.close() //保证最后关闭body
        fmt.println("status code:", res.statuscode) // 获取状态码
        // 有gzip压缩时,需要解压缩读取返回内容
        if res.header.get("content-encoding") == "gzip" {
            reader, _ := gzip.newreader(res.body) // gzip解压缩
            defer reader.close()
            io.copy(os.stdout, reader)
            os.exit(0) // 正常退出
        }
        // 无gzip压缩, 读取返回内容
        body, _ := ioutil.readall(res.body)
        fmt.println(string(body))
    }
}

csharp

标准库
using system;
using system.text;
using system.net;
using system.io;
using system.io.compression;
namespace csharp_api
{
    class program
    {
        static void main(string[] args)
        {
            // api链接
            string api_url = "http://dev.kdlapi.com/api/getproxy/?orderid=96518362xxxxxx&num=100&protocol=1&method=2&an_ha=1&sep=1";
            // 请求目标网页
            httpwebrequest request = (httpwebrequest)webrequest.create(api_url);
            request.method = "get";
            request.headers.add("accept-encoding", "gzip");  // 使用gzip压缩传输数据让访问更快
            httpwebresponse response = (httpwebresponse)request.getresponse();
            console.writeline((int)response.statuscode);  // 获取状态码
            // 解压缩读取返回内容
            using (streamreader reader =  new streamreader(new gzipstream(response.getresponsestream(), compressionmode.decompress))) {
                console.writeline(reader.readtoend());
            }
        }
    }
}

node.js

内置http模块
const http = require('http');  // 引入内置http模块
let api_url = 'http://dev.kdlapi.com/api/getproxy/?orderid=96518362xxxxxx&num=100&protocol=1&method=2&an_ha=1&sep=1';  // 要访问的目标网页
// 采用gzip压缩, 使速度更快
let options = {
    "headers" : {
        "accept-encoding": "gzip"
    }
};
// 发起请求
http.get(api_url, options, (res) => {
    // 若有gzip压缩, 则解压缩再输出
    if (res.headers['content-encoding'] && res.headers['content-encoding'].indexof('gzip') != -1) {
        let zlib = require('zlib');
        let gunzipstream = zlib.creategunzip();
        res.pipe(gunzipstream).pipe(process.stdout);
    } else {
        // 无gzip压缩,直接输出
        res.pipe(process.stdout);
    }
}).on("error", (err) => {
    // 错误处理
    console.log("error: "  err.message);
})

ruby

net/http

net/http
# -*- coding: utf-8 -*-
require 'net/http'  # 引入内置net/http模块
require 'zlib'
require 'stringio'
# 要访问的目标网页, 以京东尊龙现金一下首页为例
page_url = 'https://www.jd.com'
uri = uri(page_url)
# 创建新的请求对象 
req = net::http::get.new(uri)
# 设置user-agent
req['user-agent'] = 'mozilla/5.0 (macintosh; u; intel mac os x 10_6_8; en-us) applewebkit/534.50 (khtml, like gecko) version/5.1 safari/534.50'
req['accept-encoding'] = 'gzip'  # 使用gzip压缩传输数据让访问更快
# 发起请求, 若访问的是http网页, 请将use_ssl设为false
res = net::http.start(uri.hostname, uri.port, :use_ssl => true) {|http|
    http.request(req)
}
# 输出状态码
puts "status code: #{res.code}"
# 输出响应体
if  res.code.to_i != 200 then
    puts "page content: #{res.body}"
else
    gz = zlib::gzipreader.new(stringio.new(res.body.to_s))
    puts "page content: #{gz.read}" 
end

httparty

httparty

使用提示

请先安装httparty模块: gem install httparty

require "httparty"  # 引入httparty模块
require 'zlib'
require 'stringio'
# 要访问的目标网页, 以京东尊龙现金一下首页为例
page_url = 'https://www.jd.com'
# 设置headers
headers = {
    "user-agent" => "mozilla/5.0 (macintosh; u; intel mac os x 10_6_8; en-us) applewebkit/534.50 (khtml, like gecko) version/5.1 safari/534.50",
    "accept-encoding" => "gzip",
}
# 发起请求
res = httparty.get(page_url, :headers => headers)
# 输出状态码
puts "status code: #{res.code}"
# 输出响应体
if  res.code.to_i != 200 then
    puts "page content: #{res.body}"
else
    gz = zlib::gzipreader.new(stringio.new(res.body.to_s))
    puts "page content: #{gz.read}" 
end

php

guzzle

guzzle

使用提示

是一个简单强大的http客户端库,需要安装才能使用:
1. 安装composer curl -ss https://getcomposer.org/installer | php
2. 安装guzzle php composer.phar require guzzlehttp/guzzle:~6.0


require 'vendor/autoload.php';
use guzzlehttp\client;
//api链接
$api_url = "http://dev.kdlapi.com/api/getproxy/?orderid=96518362xxxxxx&num=100&protocol=1&method=2&an_ha=1&sep=1";
$client = new client();
$res = $client->request('get', $api_url, [
    'headers' => [
        'accept-encoding' => 'gzip'  // 使用gzip压缩让数据传输更快
    ]
]);
echo $res->getstatuscode(); //获取reponse的返回码
echo "\n\n";
echo $res->getbody(); //获取api返回内容
?>

stream

使用stream流

// gzip解压缩函数
if (!function_exists('gzdecode')) {
    function gzdecode($data) {
        // strip header and footer and inflate
        return gzinflate(substr($data, 10, -8));
    }
}
//api链接
$api_url = "http://dev.kdlapi.com/api/getproxy/?orderid=96518362xxxxxx&num=100&protocol=1&method=2&an_ha=1&sep=1";
$opts = array('http' =>
    array(
        'method'  => 'get',
        'header'  => 'accept-encoding: gzip',  // 使用gzip压缩让数据传输更快
    )
);
$context = stream_context_create($opts);
$result = file_get_contents($api_url, false, $context);
echo gzdecode($result);  // 输出返回内容
?>

curl

curl

    //api链接
    $api_url = "http://dev.kdlapi.com/api/getproxy/?orderid=96518362xxxxxx&num=100&protocol=1&method=2&an_ha=1&sep=1";
    $ch = curl_init();
    curl_setopt($ch, curlopt_url, $api_url);
    curl_setopt($ch, curlopt_ssl_verifypeer, false);  
    curl_setopt($ch, curlopt_ssl_verifyhost, false);
    curl_setopt($ch, curlopt_encoding, 'gzip'); //使用gzip压缩传输数据让访问更快
    curl_setopt($ch, curlopt_connecttimeout, 3);
    curl_setopt($ch, curlopt_timeout, 5);
    curl_setopt($ch, curlopt_header, true);
    curl_setopt($ch, curlopt_returntransfer, true);
    $result = curl_exec($ch);
    $info = curl_getinfo($ch);
    curl_close($ch);
    echo $result;
    echo "\n\nfetch ".$info['url']."\ntimeuse: ".$info['total_time']."s\n\n";
?>
联系尊龙人生就是搏
  • 售前在线咨询
    咨询享免费测试,专业工程师提供尊龙现金一下的技术支持
  • 客服热线
     周一至周六 9:00-18:00
  • 提交工单
    您的每一次反馈我们都认真对待
  • 客服微信 & qq
    客服微信:,客服qq:
  • 企业客户通道
    提交需求后专业的售前工程师为您提供服务