汇率
外汇报价,货币汇率
基本说明:
接口地址:http://op.juhe.cn/onebox/exchange/query
返回格式:json
请求方式:get
请求示例:http://op.juhe.cn/onebox/exchange/query?key=您申请的APPKEY
请求参数说明:
名称 类型 必填 说明
key string 必填 应用APPKEY,申请数据系统分配
返回参数说明:
名称 类型 说明
error_code int 返回码
reason string 返回说明
result string 返回结果集
JSON返回示例:
{
	"reason": "查询成功",
	"result": {
		"update": "2016-07-22 10:32:31",
		"list": [
			[
				"美元", /*货币名称*/
				"100", /*交易单位*/
				"665.63", /*现汇买入价*/
				"660.3", /*现钞买入价*/
				"668.3", /*现钞卖出价*/
				"666.69" /*中行折算价*/
			],
			[
				"港币",
				"100",
				"85.83",
				"85.14",
				"86.15",
				"85.96"
			],
			[
				"日元",
				"100",
				"6.2771",
				"6.0834",
				"6.3211",
				"6.3014"
			],
			[
				"欧元",
				"100",
				"732.74",
				"710.13",
				"737.88",
				"735.79"
			],
			[
				"英镑",
				"100",
				"879.28",
				"852.15",
				"885.46",
				"879.01"
			]
		]
	},
	"error_code": 0
}
服务级错误码参照
错误码 说明
208001 货币兑换名称不能为空
208002 查询不到汇率相关信息
208003 网络错误,请重试
208004 查询不到常用货币相关信息
208005 不存在的货币种类
208006 查询不到该货币兑换相关信息
10001 错误的请求KEY
10002 该KEY无请求权限
10003 KEY过期
10004 错误的OPENID
10005 应用未审核超时,请提交认证
10007 未知的请求源
10008 被禁止的IP
10009 被禁止的KEY
10011 当前IP请求超过限制
10012 请求超过次数限制
10013 测试KEY超过请求限制
10014 系统内部异常<font color="red">(调用充值类业务时,请务必联系客服或通过订单查询接口检测订单,避免造成损失)</font>
10020 接口维护
10021 接口停用
完整教学代码示例
package main
import (
    "io/ioutil"
    "net/http"
    "net/url"
    "fmt"
    "encoding/json"
)
 
//----------------------------------
// 汇率调用示例代码 - 聚合数据
// 在线接口文档:http://www.juhe.cn/docs/80
//----------------------------------
 
const APPKEY = "*******************" //您申请的APPKEY
 
func main(){
 
    //1.常用汇率查询
    Request1()
 
    //2.货币列表
    Request2()
 
    //3.实时汇率查询换算
    Request3()
 
}
 
//1.常用汇率查询
func Request1(){
    //请求地址
    juheURL :="http://op.juhe.cn/onebox/exchange/query"
 
    //初始化参数
    param:=url.Values{}
 
    //配置请求参数,方法内部已处理urlencode问题,中文参数可以直接传参
    param.Set("key",APPKEY) //应用APPKEY(应用详细页查询)
 
 
    //发送请求
    data,err:=Get(juheURL,param)
    if err!=nil{
        fmt.Errorf("请求失败,错误信息:
%v",err)
    }else{
        var netReturn map[string]interface{}
        json.Unmarshal(data,&netReturn)
        if netReturn["error_code"].(float64)==0{
            fmt.Printf("接口返回result字段是:
%v",netReturn["result"])
        }
    }
}
 
//2.货币列表
func Request2(){
    //请求地址
    juheURL :="http://op.juhe.cn/onebox/exchange/list"
 
    //初始化参数
    param:=url.Values{}
 
    //配置请求参数,方法内部已处理urlencode问题,中文参数可以直接传参
    param.Set("key",APPKEY) //应用APPKEY(应用详细页查询)
 
 
    //发送请求
    data,err:=Get(juheURL,param)
    if err!=nil{
        fmt.Errorf("请求失败,错误信息:
%v",err)
    }else{
        var netReturn map[string]interface{}
        json.Unmarshal(data,&netReturn)
        if netReturn["error_code"].(float64)==0{
            fmt.Printf("接口返回result字段是:
%v",netReturn["result"])
        }
    }
}
 
//3.实时汇率查询换算
func Request3(){
    //请求地址
    juheURL :="http://op.juhe.cn/onebox/exchange/currency"
 
    //初始化参数
    param:=url.Values{}
 
    //配置请求参数,方法内部已处理urlencode问题,中文参数可以直接传参
    param.Set("from","") //转换汇率前的货币代码
    param.Set("to","") //转换汇率成的货币代码
    param.Set("key",APPKEY) //应用APPKEY(应用详细页查询)
 
 
    //发送请求
    data,err:=Get(juheURL,param)
    if err!=nil{
        fmt.Errorf("请求失败,错误信息:
%v",err)
    }else{
        var netReturn map[string]interface{}
        json.Unmarshal(data,&netReturn)
        if netReturn["error_code"].(float64)==0{
            fmt.Printf("接口返回result字段是:
%v",netReturn["result"])
        }
    }
}
 
 
 
// get 网络请求
func Get(apiURL string,params url.Values)(rs[]byte ,err error){
    var Url *url.URL
    Url,err=url.Parse(apiURL)
    if err!=nil{
        fmt.Printf("解析url错误:
%v",err)
        return nil,err
    }
    //如果参数中有中文参数,这个方法会进行URLEncode
    Url.RawQuery=params.Encode()
    resp,err:=http.Get(Url.String())
    if err!=nil{
        fmt.Println("err:",err)
        return nil,err
    }
    defer resp.Body.Close()
    return ioutil.ReadAll(resp.Body)
}
 
// post 网络请求 ,params 是url.Values类型
func Post(apiURL string, params url.Values)(rs[]byte,err error){
    resp,err:=http.PostForm(apiURL, params)
    if err!=nil{
        return nil ,err
    }
    defer resp.Body.Close()
    return ioutil.ReadAll(resp.Body)
}
<?php
header('Content-type:text/html;charset=utf-8');


//配置您申请的appkey
$appkey = "*********************";




//************1.常用汇率查询************
$url = "http://op.juhe.cn/onebox/exchange/query";
$params = array(
    "key" => $appkey,//应用APPKEY(应用详细页查询)
);
$paramstring = http_build_query($params);
$content = juhecurl($url,$paramstring);
$result = json_decode($content,true);
if($result){
    if($result['error_code']=='0'){
        print_r($result);
    }else{
        echo $result['error_code'].":".$result['reason'];
    }
}else{
    echo "请求失败";
}
//**************************************************




//************2.货币列表************
$url = "http://op.juhe.cn/onebox/exchange/list";
$params = array(
    "key" => $appkey,//应用APPKEY(应用详细页查询)
);
$paramstring = http_build_query($params);
$content = juhecurl($url,$paramstring);
$result = json_decode($content,true);
if($result){
    if($result['error_code']=='0'){
        print_r($result);
    }else{
        echo $result['error_code'].":".$result['reason'];
    }
}else{
    echo "请求失败";
}
//**************************************************




//************3.实时汇率查询换算************
$url = "http://op.juhe.cn/onebox/exchange/currency";
$params = array(
    "from" => "",//转换汇率前的货币代码
    "to" => "",//转换汇率成的货币代码
    "key" => $appkey,//应用APPKEY(应用详细页查询)
);
$paramstring = http_build_query($params);
$content = juhecurl($url,$paramstring);
$result = json_decode($content,true);
if($result){
    if($result['error_code']=='0'){
        print_r($result);
    }else{
        echo $result['error_code'].":".$result['reason'];
    }
}else{
    echo "请求失败";
}
//**************************************************





/**
 * 请求接口返回内容
 * @param  string $url [请求的URL地址]
 * @param  string $params [请求的参数]
 * @param  int $ipost [是否采用POST形式]
 * @return  string
 */
function juhecurl($url,$params=false,$ispost=0){
    $httpInfo = array();
    $ch = curl_init();

    curl_setopt( $ch, CURLOPT_HTTP_VERSION , CURL_HTTP_VERSION_1_1 );
    curl_setopt( $ch, CURLOPT_USERAGENT , 'JuheData' );
    curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT , 60 );
    curl_setopt( $ch, CURLOPT_TIMEOUT , 60);
    curl_setopt( $ch, CURLOPT_RETURNTRANSFER , true );
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    if( $ispost )
    {
        curl_setopt( $ch , CURLOPT_POST , true );
        curl_setopt( $ch , CURLOPT_POSTFIELDS , $params );
        curl_setopt( $ch , CURLOPT_URL , $url );
    }
    else
    {
        if($params){
            curl_setopt( $ch , CURLOPT_URL , $url.'?'.$params );
        }else{
            curl_setopt( $ch , CURLOPT_URL , $url);
        }
    }
    $response = curl_exec( $ch );
    if ($response === FALSE) {
        //echo "cURL Error: " . curl_error($ch);
        return false;
    }
    $httpCode = curl_getinfo( $ch , CURLINFO_HTTP_CODE );
    $httpInfo = array_merge( $httpInfo , curl_getinfo( $ch ) );
    curl_close( $ch );
    return $response;
}
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
 
import net.sf.json.JSONObject;
 
/**
*汇率调用示例代码 - 聚合数据
*在线接口文档:http://www.juhe.cn/docs/80
**/
 
public class JuheDemo {
    public static final String DEF_CHATSET = "UTF-8";
    public static final int DEF_CONN_TIMEOUT = 30000;
    public static final int DEF_READ_TIMEOUT = 30000;
    public static String userAgent =  "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.66 Safari/537.36";
 
    //配置您申请的KEY
    public static final String APPKEY ="*************************";
 
    //1.常用汇率查询
    public static void getRequest1(){
        String result =null;
        String url ="http://op.juhe.cn/onebox/exchange/query";//请求接口地址
        Map params = new HashMap();//请求参数
            params.put("key",APPKEY);//应用APPKEY(应用详细页查询)
 
        try {
            result =net(url, params, "GET");
            JSONObject object = JSONObject.fromObject(result);
            if(object.getInt("error_code")==0){
                System.out.println(object.get("result"));
            }else{
                System.out.println(object.get("error_code")+":"+object.get("reason"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
    //2.货币列表
    public static void getRequest2(){
        String result =null;
        String url ="http://op.juhe.cn/onebox/exchange/list";//请求接口地址
        Map params = new HashMap();//请求参数
            params.put("key",APPKEY);//应用APPKEY(应用详细页查询)
 
        try {
            result =net(url, params, "GET");
            JSONObject object = JSONObject.fromObject(result);
            if(object.getInt("error_code")==0){
                System.out.println(object.get("result"));
            }else{
                System.out.println(object.get("error_code")+":"+object.get("reason"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
    //3.实时汇率查询换算
    public static void getRequest3(){
        String result =null;
        String url ="http://op.juhe.cn/onebox/exchange/currency";//请求接口地址
        Map params = new HashMap();//请求参数
            params.put("from","");//转换汇率前的货币代码
            params.put("to","");//转换汇率成的货币代码
            params.put("key",APPKEY);//应用APPKEY(应用详细页查询)
 
        try {
            result =net(url, params, "GET");
            JSONObject object = JSONObject.fromObject(result);
            if(object.getInt("error_code")==0){
                System.out.println(object.get("result"));
            }else{
                System.out.println(object.get("error_code")+":"+object.get("reason"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
 
 
    public static void main(String[] args) {
 
    }
 
    /**
     *
     * @param strUrl 请求地址
     * @param params 请求参数
     * @param method 请求方法
     * @return  网络请求字符串
     * @throws Exception
     */
    public static String net(String strUrl, Map params,String method) throws Exception {
        HttpURLConnection conn = null;
        BufferedReader reader = null;
        String rs = null;
        try {
            StringBuffer sb = new StringBuffer();
            if(method==null || method.equals("GET")){
                strUrl = strUrl+"?"+urlencode(params);
            }
            URL url = new URL(strUrl);
            conn = (HttpURLConnection) url.openConnection();
            if(method==null || method.equals("GET")){
                conn.setRequestMethod("GET");
            }else{
                conn.setRequestMethod("POST");
                conn.setDoOutput(true);
            }
            conn.setRequestProperty("User-agent", userAgent);
            conn.setUseCaches(false);
            conn.setConnectTimeout(DEF_CONN_TIMEOUT);
            conn.setReadTimeout(DEF_READ_TIMEOUT);
            conn.setInstanceFollowRedirects(false);
            conn.connect();
            if (params!= null && method.equals("POST")) {
                try {
                    DataOutputStream out = new DataOutputStream(conn.getOutputStream());
                        out.writeBytes(urlencode(params));
                } catch (Exception e) {
                    // TODO: handle exception
                }
            }
            InputStream is = conn.getInputStream();
            reader = new BufferedReader(new InputStreamReader(is, DEF_CHATSET));
            String strRead = null;
            while ((strRead = reader.readLine()) != null) {
                sb.append(strRead);
            }
            rs = sb.toString();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                reader.close();
            }
            if (conn != null) {
                conn.disconnect();
            }
        }
        return rs;
    }
 
    //将map型转为请求参数型
    public static String urlencode(Map<String,Object>data) {
        StringBuilder sb = new StringBuilder();
        for (Map.Entry i : data.entrySet()) {
            try {
                sb.append(i.getKey()).append("=").append(URLEncoder.encode(i.getValue()+"","UTF-8")).append("&");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }
}
#!/usr/bin/python
# -*- coding: utf-8 -*-
import json, urllib
from urllib import urlencode
 
#----------------------------------
# 汇率调用示例代码 - 聚合数据
# 在线接口文档:http://www.juhe.cn/docs/80
#----------------------------------
 
def main():
 
    #配置您申请的APPKey
    appkey = "*********************"
 
    #1.常用汇率查询
    request1(appkey,"GET")
 
    #2.货币列表
    request2(appkey,"GET")
 
    #3.实时汇率查询换算
    request3(appkey,"GET")
 
 
 
#常用汇率查询
def request1(appkey, m="GET"):
    url = "http://op.juhe.cn/onebox/exchange/query"
    params = {
        "key" : appkey, #应用APPKEY(应用详细页查询)
 
    }
    params = urlencode(params)
    if m =="GET":
        f = urllib.urlopen("%s?%s" % (url, params))
    else:
        f = urllib.urlopen(url, params)
 
    content = f.read()
    res = json.loads(content)
    if res:
        error_code = res["error_code"]
        if error_code == 0:
            #成功请求
            print res["result"]
        else:
            print "%s:%s" % (res["error_code"],res["reason"])
    else:
        print "request api error"
 
#货币列表
def request2(appkey, m="GET"):
    url = "http://op.juhe.cn/onebox/exchange/list"
    params = {
        "key" : appkey, #应用APPKEY(应用详细页查询)
 
    }
    params = urlencode(params)
    if m =="GET":
        f = urllib.urlopen("%s?%s" % (url, params))
    else:
        f = urllib.urlopen(url, params)
 
    content = f.read()
    res = json.loads(content)
    if res:
        error_code = res["error_code"]
        if error_code == 0:
            #成功请求
            print res["result"]
        else:
            print "%s:%s" % (res["error_code"],res["reason"])
    else:
        print "request api error"
 
#实时汇率查询换算
def request3(appkey, m="GET"):
    url = "http://op.juhe.cn/onebox/exchange/currency"
    params = {
        "from" : "", #转换汇率前的货币代码
        "to" : "", #转换汇率成的货币代码
        "key" : appkey, #应用APPKEY(应用详细页查询)
 
    }
    params = urlencode(params)
    if m =="GET":
        f = urllib.urlopen("%s?%s" % (url, params))
    else:
        f = urllib.urlopen(url, params)
 
    content = f.read()
    res = json.loads(content)
    if res:
        error_code = res["error_code"]
        if error_code == 0:
            #成功请求
            print res["result"]
        else:
            print "%s:%s" % (res["error_code"],res["reason"])
    else:
        print "request api error"
 
 
 
if __name__ == '__main__':
    main()
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using Xfrog.Net;
using System.Diagnostics;
using System.Web;
 
//----------------------------------
// 汇率调用示例代码 - 聚合数据
// 在线接口文档:http://www.juhe.cn/docs/80
// 代码中JsonObject类下载地址:http://download.csdn.net/download/gcm3206021155665/7458439
//----------------------------------
 
namespace ConsoleAPI
{
    class Program
    {
        static void Main(string[] args)
        {
            string appkey = "*******************"; //配置您申请的appkey
 
             
            //1.常用汇率查询
            string url1 = "http://op.juhe.cn/onebox/exchange/query";
 
            var parameters1 = new Dictionary<string, string>();
 
            parameters1.Add("key", appkey);//你申请的key
 
            string result1 = sendPost(url1, parameters1, "get");
 
            JsonObject newObj1 = new JsonObject(result1);
            String errorCode1 = newObj1["error_code"].Value;
 
            if (errorCode1 == "0")
            {
                Debug.WriteLine("成功");
                Debug.WriteLine(newObj1);
            }
            else
            {
                //Debug.WriteLine("失败");
                Debug.WriteLine(newObj1["error_code"].Value+":"+newObj1["reason"].Value);
            }
 
 
            //2.货币列表
            string url2 = "http://op.juhe.cn/onebox/exchange/list";
 
            var parameters2 = new Dictionary<string, string>();
 
            parameters2.Add("key", appkey);//你申请的key
 
            string result2 = sendPost(url2, parameters2, "get");
 
            JsonObject newObj2 = new JsonObject(result2);
            String errorCode2 = newObj2["error_code"].Value;
 
            if (errorCode2 == "0")
            {
                Debug.WriteLine("成功");
                Debug.WriteLine(newObj2);
            }
            else
            {
                //Debug.WriteLine("失败");
                Debug.WriteLine(newObj2["error_code"].Value+":"+newObj2["reason"].Value);
            }
 
 
            //3.实时汇率查询换算
            string url3 = "http://op.juhe.cn/onebox/exchange/currency";
 
            var parameters3 = new Dictionary<string, string>();
 
            parameters3.Add("from" , ""); //转换汇率前的货币代码
            parameters3.Add("to" , ""); //转换汇率成的货币代码
            parameters3.Add("key", appkey);//你申请的key
 
            string result3 = sendPost(url3, parameters3, "get");
 
            JsonObject newObj3 = new JsonObject(result3);
            String errorCode3 = newObj3["error_code"].Value;
 
            if (errorCode3 == "0")
            {
                Debug.WriteLine("成功");
                Debug.WriteLine(newObj3);
            }
            else
            {
                //Debug.WriteLine("失败");
                Debug.WriteLine(newObj3["error_code"].Value+":"+newObj3["reason"].Value);
            }
 
 
        }
 
        /// <summary>
        /// Http (GET/POST)
        /// </summary>
        /// <param name="url">请求URL</param>
        /// <param name="parameters">请求参数</param>
        /// <param name="method">请求方法</param>
        /// <returns>响应内容</returns>
        static string sendPost(string url, IDictionary<string, string> parameters, string method)
        {
            if (method.ToLower() == "post")
            {
                HttpWebRequest req = null;
                HttpWebResponse rsp = null;
                System.IO.Stream reqStream = null;
                try
                {
                    req = (HttpWebRequest)WebRequest.Create(url);
                    req.Method = method;
                    req.KeepAlive = false;
                    req.ProtocolVersion = HttpVersion.Version10;
                    req.Timeout = 5000;
                    req.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
                    byte[] postData = Encoding.UTF8.GetBytes(BuildQuery(parameters, "utf8"));
                    reqStream = req.GetRequestStream();
                    reqStream.Write(postData, 0, postData.Length);
                    rsp = (HttpWebResponse)req.GetResponse();
                    Encoding encoding = Encoding.GetEncoding(rsp.CharacterSet);
                    return GetResponseAsString(rsp, encoding);
                }
                catch (Exception ex)
                {
                    return ex.Message;
                }
                finally
                {
                    if (reqStream != null) reqStream.Close();
                    if (rsp != null) rsp.Close();
                }
            }
            else
            {
                //创建请求
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url + "?" + BuildQuery(parameters, "utf8"));
 
                //GET请求
                request.Method = "GET";
                request.ReadWriteTimeout = 5000;
                request.ContentType = "text/html;charset=UTF-8";
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream myResponseStream = response.GetResponseStream();
                StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
 
                //返回内容
                string retString = myStreamReader.ReadToEnd();
                return retString;
            }
        }
 
        /// <summary>
        /// 组装普通文本请求参数。
        /// </summary>
        /// <param name="parameters">Key-Value形式请求参数字典</param>
        /// <returns>URL编码后的请求数据</returns>
        static string BuildQuery(IDictionary<string, string> parameters, string encode)
        {
            StringBuilder postData = new StringBuilder();
            bool hasParam = false;
            IEnumerator<KeyValuePair<string, string>> dem = parameters.GetEnumerator();
            while (dem.MoveNext())
            {
                string name = dem.Current.Key;
                string value = dem.Current.Value;
                // 忽略参数名或参数值为空的参数
                if (!string.IsNullOrEmpty(name))//&& !string.IsNullOrEmpty(value)
                {
                    if (hasParam)
                    {
                        postData.Append("&");
                    }
                    postData.Append(name);
                    postData.Append("=");
                    if (encode == "gb2312")
                    {
                        postData.Append(HttpUtility.UrlEncode(value, Encoding.GetEncoding("gb2312")));
                    }
                    else if (encode == "utf8")
                    {
                        postData.Append(HttpUtility.UrlEncode(value, Encoding.UTF8));
                    }
                    else
                    {
                        postData.Append(value);
                    }
                    hasParam = true;
                }
            }
            return postData.ToString();
        }
 
        /// <summary>
        /// 把响应流转换为文本。
        /// </summary>
        /// <param name="rsp">响应流对象</param>
        /// <param name="encoding">编码方式</param>
        /// <returns>响应文本</returns>
        static string GetResponseAsString(HttpWebResponse rsp, Encoding encoding)
        {
            System.IO.Stream stream = null;
            StreamReader reader = null;
            try
            {
                // 以字符流的方式读取HTTP响应
                stream = rsp.GetResponseStream();
                reader = new StreamReader(stream, encoding);
                return reader.ReadToEnd();
            }
            finally
            {
                // 释放资源
                if (reader != null) reader.Close();
                if (stream != null) stream.Close();
                if (rsp != null) rsp.Close();
            }
        }
    }
}