| 环境 | apiHost | 注意事项 |
|---|---|---|
| 线上环境 | https://api.hhefl.com | 测试过程需要使用真实纳税人账号 |
| 参数名称 | 参数类型 | 说明 |
|---|---|---|
| Content-Type | String | 请填写application/json;charset=UTF-8 |
| access_token | String | 大多数接口,需要通过验证身份以后才能访问,需要携带该头信息;请从OAuth接口获取的access_token |
| req_date | Long | 当前时间戳的毫秒数。可以参考java的System.currentTimeMillis()方法生成;(如果未携带该头信息,或与服务端的时间差超过 15 分钟,则云端拒绝该请求) |
| req_sign | String | 签名校验请求的合法性 |
| 参数名称 | 参数类型 | 说明 |
|---|---|---|
| code | String | 业务编码 |
| success | Boolean | 接口是否成功(是否发生业务异常) |
| reqId | String | 由服务器端生成的唯一标识,对应每次请求。排查接口异常时,可提供该字段方便定位 |
| message | String | 业务异常信息 |
| data | Oject | 业务数据 |
{
"reqId": "5b8d41f68b0d47a49dca4a4812857d49",
"code": "2000",
"success": true,
"message": null,
"data": {
"access_token": "eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJbLTEsLTEsLTEsMTAwLFwiXCIsMdIiwiZXhwIjoxNzQwNjIzMTUwLCJpYXQiOjE3MzkzMjcxNTB9.1z55Yzm37AKuQcWlbjg1IaEw9BECCsFp9s6g_or9wyLa5RNmdlA2Kfu_GtRuWuVvkk6ArPjVFtBrcNw",
"code": null,
"error_msg": null,
"expires_in": 7200,
"orgId": null,
"refresh_token": "eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJbLTEsLTEsLTEsMTsbCxcIlwiLC0xLG51bGxdIiwiZXhwIjoxNzQxOTE5MTUwLCJpYXQiOjE3MzkzMjcxNTB9.kOW2Cu5O5th58NUJDlDnhu3ircfG45e2vCjUs0QAPlydHQcd6pZRAu9jgg1MmSbioHUs7f4hBsPEw",
"result": true,
"token_parameter": null,
"token_type": null,
"userId": null
}
}{
"reqId": "8146864387cd4847801616abd9e2f16a",
"code": "2000",
"success": true,
"message": null,
"data": {
"error_msg": "应用的密钥无效!",
}
}req_sign: API-SV1:<AppKey>:<Signature>待签名字符串 = HTTPMethod + "_" + Content-Md5 + "_" + req_date + "_" + access_token + "_" + AppSecret签名值 = Base64(MD5(待签名字符串)))| 签名示例 | 执行结果 | 示例描述 |
| 请求body: {"nsrsbh":"915211111111111111"} | 请求body Md5结果: Content-Md5=4e7f9b81e299ad014cfbc6949c3f4e04 | 请注意空格换行等空白字符,如果POST请求body内容包含空格换行等空白字符,请签名用的字符串也包含,保持和POST请求body一致,最简单的做法是请求body和计算签名都去掉空白字符串 |
| 待签名字符串: signStr=HTTPMethod_Content-Md5_req_date_accessToken_appSecret =POST_4e7f9b81e299ad014cfbc6949c3f4e04_xxx_yyy_zzz | 签名前:POST_4e7f9b81e299ad014cfbc6949c3f4e04_1581588537349_eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJbLTEsLTEsLTEsMTAwLFwiXCIsMTAwMDEwMDEsbnVsbCxcIlwiLC0xXSIsImV4cCI6MTU4Mjg4Mjg0NSwiaWF0IjoxNTgxNTg2ODQ1fQ.T4GTFFzf6xD2n1rrCFVu88dQA8ipEobX2_i-Ub7qvIkxrTScmUm_113r1VEsTGhysA-jLFVwFWOtRqEaWvIvVA_9r27FCIHtmIAUBoNjA5Z5hq2vTCEfAL82YzrnV4vdlhpXAp2 签名 md5后: a41cc679d3c2303933d0acb002c18b14 继续base64之后最终签名值: freq_signMD5=YTQxY2M2NzlkM2MyMzAzOTMzZDBhY2IwMDJjMThiMTQ= | 1、xxx请替换成实际的时间戳,类似1581588537349的格式 2、yyy请替换成实际取到的accessToken, 类似 eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJbLTEsLTEsLTEsMTAwLFwiXCIsMTAwMDEwMDEsbnVsbCxcIlwiLC0xXSIsImV4cCI6MTU4Mjg4Mjg0NSwiaWF0IjoxNTgxNTg2ODQ1fQ.T4GTFFzf6xD2n1rrCFVu88dQA8ipEobX2_i-Ub7qvIkxrTScmUm_113r1VEsTGhysA-jLFVwFWOtRqEaWvIvVA 3、zzz请替换成实际的appSecret,类似 9r27FCIHtmIAUBoNjA5Z5hq2vTCEfAL82YzrnV4vdlhpXAp2 |
| req_sign=API-SV1:appKey :freq_signMD5 | 最终请求header,req_sign的值: API-SV1:1000xxxx:YTQxY2M2NzlkM2MyMzAzOTMzZDBhY2IwMDJjMThiMTQ= | 1000xxxx请替换为实际的appkey |
<!-- Bouncy Castle for SM4 encryption -->
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk15on</artifactId>
<version>1.70</version>
</dependency>
private static final String ALGORITHM_NAME = "SM4";
private static final String MODE = "CBC";
private static final String PADDING = "PKCS5Padding";
private static final String secretKeyHex = "开放平台中获取";
/**
* 生成随机 IV
*
* @return 十六进制字符串格式的 IV(32字符)
*/
private String generateRandomIV() {
byte[] iv = new byte[16];
SecureRandom random = new SecureRandom();
random.nextBytes(iv);
return bytesToHex(iv);
}
/**
* 加密
* @param plainText 需要加密的文本
* @return
* @throws Exception
*/
public String encrypt(String plainText) throws Exception {
// 每次加密生成随机 IV
String ivHex = generateRandomIV();
// 转换密钥和IV
byte[] keyBytes = hexStringToBytes(secretKeyHex);
byte[] ivBytes = hexStringToBytes(ivHex);
// 创建密钥规范
SecretKeySpec keySpec = new SecretKeySpec(keyBytes, ALGORITHM_NAME);
IvParameterSpec ivSpec = new IvParameterSpec(ivBytes);
// 创建Cipher
String transformation = ALGORITHM_NAME + "/" + MODE + "/" + PADDING;
Cipher cipher = Cipher.getInstance(transformation, BouncyCastleProvider.PROVIDER_NAME);
cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);
// 加密
byte[] encryptedBytes = cipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8));
// Base64编码
return Base64.getEncoder().encodeToString(encryptedBytes);
}
/**
* 解密
* @param cipherText 需要解密的文本
* @param headerIV 获取加密时header中IV
* @return
* @throws Exception
*/
public String decrypt(String cipherText,String headerIV) throws Exception {
// 获取当前请求的 IV(用于解密响应)
String ivHex = headerIV;
if (ivHex == null) {
throw new IllegalStateException("未找到 IV 向量,请先调用 encrypt 方法");
}
// Base64解码
byte[] encryptedBytes = Base64.getDecoder().decode(cipherText);
// 转换密钥和IV
byte[] keyBytes = hexStringToBytes(secretKeyHex);
byte[] ivBytes = hexStringToBytes(ivHex);
// 创建密钥规范
SecretKeySpec keySpec = new SecretKeySpec(keyBytes, ALGORITHM_NAME);
IvParameterSpec ivSpec = new IvParameterSpec(ivBytes);
// 创建Cipher
String transformation = ALGORITHM_NAME + "/" + MODE + "/" + PADDING;
Cipher cipher = Cipher.getInstance(transformation, BouncyCastleProvider.PROVIDER_NAME);
cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
// 解密
byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
return new String(decryptedBytes, StandardCharsets.UTF_8);
} import com.alibaba.fastjson.JSONObject;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
public class QxyApiHttpDemo {
// 对接地址apiHost
private static final String url = "https://api.hhefl.com";
private static final String AppKey = "1000****";//分配的appkey
private static final String AppSecret = "*****************************************";//分配的AppSecret
private static String access_token = null;
/**
* 获取access_token
* @return
* @throws Exception
*/
private static String getAccessToken() throws Exception {
String tokenUrl = url + "/v2/public/oauth2/login";
String body = "{\"grant_type\":\"client_credentials\",\"client_appkey\":\"" + AppKey + "\",\"client_secret\":\"" + md5(AppSecret) + "\"}";
HttpURLConnection conn = (HttpURLConnection) new URL(tokenUrl).openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
conn.setDoOutput(true);
try (DataOutputStream wr = new DataOutputStream(conn.getOutputStream())) {
wr.write(body.getBytes(StandardCharsets.UTF_8));
}
String response = readResponse(conn);
System.out.println("示例获取token结果:" + response);
JSONObject resultJson = JSONObject.parseObject(response);
JSONObject dataJson = resultJson.getJSONObject("data");
return dataJson.getString("access_token");
}
/**
* http发送业务请求
* @param path
* @param body
* @return
* @throws Exception
*/
private static void sendBusinessRequest(String path, String body) throws Exception {
String fullUrl = url + path;
String req_date = String.valueOf(System.currentTimeMillis());
String contentMd5 = md5(body);
// 生成待签名字符串并进行UTF-8编码
String toSign = "POST_" + contentMd5 + "_" + req_date + "_" + access_token + "_" + AppSecret;
byte[] toSignBytes = toSign.getBytes(StandardCharsets.UTF_8);
String toSignUtf8 = new String(toSignBytes, StandardCharsets.UTF_8);
// 生成MD5加密结果
String md5Result = md5(toSignUtf8);
// 生成Base64编码结果
String base64Result = base64Encode(md5Result);
// 生成req_sign
String req_sign = "API-SV1:" + AppKey + ":" + base64Result;
HttpURLConnection conn = (HttpURLConnection) new URL(fullUrl).openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
conn.setRequestProperty("access_token", access_token);
conn.setRequestProperty("req_date", req_date);
conn.setRequestProperty("req_sign", req_sign);
conn.setDoOutput(true);
byte[] outputInBytes = body.getBytes(StandardCharsets.UTF_8);
OutputStream os = conn.getOutputStream();
os.write(outputInBytes);
os.close();
// 获取服务器响应代码
int responseCode = conn.getResponseCode();
// 读取服务器响应内容
if (responseCode == HttpURLConnection.HTTP_OK) {
String result = readResponse(conn);
System.out.println("示例返回结果:"+result);
}else {
//异常处理
}
conn.disconnect();
}
private static String readResponse(HttpURLConnection conn) throws Exception {
try (BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()))) {
String inputLine;
StringBuilder content = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
content.append(inputLine);
}
return content.toString();
}
}
private static String md5(String input) throws NoSuchAlgorithmException {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] digest = md.digest(input.getBytes(StandardCharsets.UTF_8));
return bytesToHex(digest);
}
private static String base64Encode(String input) {
byte[] inputBytes = input.getBytes(StandardCharsets.UTF_8);
return Base64.getEncoder().encodeToString(inputBytes);
}
private static String bytesToHex(byte[] bytes) {
StringBuilder hexString = new StringBuilder();
for (byte b : bytes) {
String hex = Integer.toHexString(0xff & b);
if (hex.length() == 1) hexString.append('0');
hexString.append(hex);
}
return hexString.toString();
}
public static void main(String[] args) {
try {
// 1. 获取access_token
access_token = getAccessToken();
//这里获取到的access_token需要缓存到本地缓存中再使用,频繁请求login接口会被限制。
// 2. 请求业务接口示例: 发票查验接口
String path = "/v2/invoice/cy/zzsfpCy"; // 自定义业务接口路径
String params = "{\"cyList\":[{\"fpdm\":\"34******30\",\"fphm\":\"17****68\",\"kprq\":\"2021-11-01\",\"je\":1421.63}]}";
sendBusinessRequest(path, params); // 请求body参数
} catch (Exception e) {
e.printStackTrace();
}
}
}import hashlib
import base64
import json
import requests
from datetime import datetime
# 对接地址apiHost
url = "https://api.hhefl.com"
AppKey = "1000****" # 分配的appkey
AppSecret = "***********************" # 分配的AppSecret
access_token = None
def md5(input_string):
md = hashlib.md5()
md.update(input_string.encode('utf-8'))
return md.hexdigest()
def base64_encode(input_string):
input_bytes = input_string.encode('utf-8')
return base64.b64encode(input_bytes).decode('utf-8')
# 获取access_token
def get_access_token():
global access_token
token_url = f"{url}/v2/public/oauth2/login"
body = {
"grant_type": "client_credentials",
"client_appkey": AppKey,
"client_secret": md5(AppSecret)
}
response = requests.post(token_url, json=body)
response.raise_for_status()
result_json = response.json()
data_json = result_json["data"]
access_token = data_json["access_token"]
print(f"示例获取token结果: {response.text}")
#发起业务请求
def send_business_request(path, body):
full_url = f"{url}{path}"
req_date = str(int(datetime.now().timestamp() * 1000))
content_md5 = md5(body)
# 生成待签名字符串并进行UTF-8编码
to_sign = f"POST_{content_md5}_{req_date}_{access_token}_{AppSecret}"
to_sign_utf8 = to_sign.encode('utf-8')
# 生成MD5加密结果
md5_result = md5(to_sign_utf8.decode('utf-8'))
# 生成Base64编码结果
base64_result = base64_encode(md5_result)
# 生成req_sign
req_sign = f"API-SV1:{AppKey}:{base64_result}"
headers = {
"Content-Type": "application/json;charset=UTF-8",
"access_token": access_token,
"req_date": req_date,
"req_sign": req_sign
}
response = requests.post(full_url, headers=headers, data=body)
if response.status_code == 200:
print(f"示例返回结果: {response.text}")
else:
# 异常处理
print(f"请求失败: {response.status_code}, {response.text}")
def main():
try:
# 1. 获取access_token
get_access_token()
# 获取到的access_token做缓存处理
# 2. 请求业务接口示例:数电开票-已开发票列表查询
path = "/v2/invoice/qdfp/fpcx" # 自定义业务接口路径
# 按照接口文档定义的参数进行参数封装
params = json.dumps({
"action": "fpcx",
"nsrsbh": "真实税号",
"data": {
"pageIndex": 0,
"pageSize": 10,
"params": {
"kprqq": "2024-09-01",
"kprqz": "2024-09-15",
"dfnsrsbh": "",
"dfnsrmc": "",
"fphm": ""
}
}
})
send_business_request(path, params)
except Exception as e:
print(f"发生异常: {e}")
if __name__ == "__main__":
main()
<?php
const
APPKEY = '填写自己的appkey', // 填写自己的appkey
SERCET = '填写自己的sercet', // 填写自己的sercet
TOKEN_URL ='https://api.hhefl.com/v2/public/oauth2/login', // 获取token url
REQUEST_URL = 'https://api.hhefl.com/v2/invoice/cy/zzsfpCy', // 查询发票 url
end = '';
// 获取请求参数
// 发票查询请求参数
$request = json_encode([
"cyList" => [
[
"fpdm" => "34******30",
"fphm" => "17****68",
"kprq" => "2021-11-01",
"je" => 1421.63
]
]
]);
// 获取 access_token
$token = '';
// todo token可以保存到缓存中,有效期十五天。有效期内不用重新获取,过期后再重新获取
$tokenParams = $base = [];
$tokenParams['grant_type'] = 'client_credentials';
$tokenParams['client_appkey'] = APPKEY;
$tokenParams['client_secret'] = md5(SERCET);
$tokenParams = json_encode($tokenParams);
$returnDate = posturl(TOKEN_URL, $tokenParams);
if(isset($returnDate['value']['access_token'])){
$token = $returnDate['value']['access_token'];
}else{
return '获取token失败!';
}
// 组装查询发票的参数
$base['req_date'] = time() * 1000;
$base['access_token'] =$token;
$signStr = 'POST'.'_'.md5($request).'_'.$base['req_date'].'_'.$base['access_token'].'_'.SERCET;
$signStr ='API-SV1'.':'.$tokenParams['client_appkey'].':'. base64_encode(md5($signStr));
$base['req_sign'] = $signStr;
$returnDate = posturl(REQUEST_URL, $request, $base);
print_r($returnDate);
/**
* 发送 post 请求
* @param String $url
* @param String $data
* @param Array $requestHander
* @return void
*/
function posturl(String $url, String $data, Array $requestHander=[]){
if($requestHander){
$header = array(
'Content-Type: application/json; charset=utf-8',
'req_date: '.$requestHander['req_date'],
'access_token: '.$requestHander['access_token'],
'req_sign: '.$requestHander['req_sign']
);
}else{
$header = array(
'Content-Type: application/json; charset=utf-8',
);
}
//初始化
$curl = curl_init();
//设置抓取的url
curl_setopt($curl, CURLOPT_URL, $url);
//设置头文件的信息作为数据流输出
curl_setopt($curl, CURLOPT_HEADER, 0);
//设置获取的信息以文件流的形式返回,而不是直接输出。
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
// 超时设置
curl_setopt($curl, CURLOPT_TIMEOUT, 10);
// 超时设置,以毫秒为单位
// curl_setopt($curl, CURLOPT_TIMEOUT_MS, 500);
// 设置请求头
curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE );
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE );
//设置post方式提交
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
//执行命令
$data = curl_exec($curl);
// 显示错误信息
if (curl_error($curl)) {
return "Error: " . curl_error($curl);
} else {
curl_close($curl);
return json_decode($data, true);
}
}
package main
import (
"bytes"
"crypto/md5"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"strconv"
"time"
)
// 对接地址
const url = "https://api.hhefl.com"
// AppKey 和 AppSecret
var appKey = "1000****"
var appSecret = "*****************************************"
// 全局变量用于存储 access_token
var accessToken string
// 获取 access_token
func getAccessToken() (string, error) {
tokenUrl := url + "/v2/public/oauth2/login"
body := `{"grant_type":"client_credentials","client_appkey":"` + appKey + `","client_secret":"` + md5Hash(appSecret) + `"}`
req, err := http.NewRequest("POST", tokenUrl, bytes.NewBufferString(body))
if err!= nil {
return "", err
}
req.Header.Set("Content-Type", "application/json;charset=UTF-8")
client := &http.Client{}
resp, err := client.Do(req)
if err!= nil {
return "", err
}
defer resp.Body.Close()
response, err := ioutil.ReadAll(resp.Body)
if err!= nil {
return "", err
}
fmt.Println("示例获取 token 结果:", string(response))
var result map[string]interface{}
err = json.Unmarshal(response, &result)
if err!= nil {
return "", err
}
data, ok := result["data"].(map[string]interface{})
if!ok {
return "", fmt.Errorf("无法获取 'data' 字段")
}
accessToken = data["access_token"].(string)
return accessToken, nil
}
// 发送业务请求
func sendBusinessRequest(path, body string) error {
fullUrl := url + path
reqDate := strconv.FormatInt(time.Now().UnixMilli(), 10)
contentMd5 := md5Hash(body)
// 生成待签名字符串
toSign := "POST_" + contentMd5 + "_" + reqDate + "_" + accessToken + "_" + appSecret
// 生成 MD5 加密结果
md5Result := md5Hash(toSign)
// 生成 Base64 编码结果
base64Result := base64.StdEncoding.EncodeToString([]byte(md5Result))
// 生成 req_sign
reqSign := "API-SV1:" + appKey + ":" + base64Result
req, err := http.NewRequest("POST", fullUrl, bytes.NewBufferString(body))
if err!= nil {
return err
}
req.Header.Set("Content-Type", "application/json;charset=UTF-8")
req.Header.Set("access_token", accessToken)
req.Header.Set("req_date", reqDate)
req.Header.Set("req_sign", reqSign)
client := &http.Client{}
resp, err := client.Do(req)
if err!= nil {
return err
}
defer resp.Body.Close()
responseCode := resp.StatusCode
if responseCode == http.StatusOK {
response, err := ioutil.ReadAll(resp.Body)
if err!= nil {
return err
}
fmt.Println("示例返回结果:", string(response))
} else {
// 异常处理
return fmt.Errorf("请求失败: %d", responseCode)
}
return nil
}
// MD5 哈希函数
func md5Hash(input string) string {
hasher := md5.New()
io.WriteString(hasher, input)
return fmt.Sprintf("%x", hasher.Sum(nil))
}
func main() {
var err error
accessToken, err = getAccessToken()
if err!= nil {
fmt.Println("获取 access_token 时出错:", err)
return
}
// 2. 请求业务接口示例:数电开票-已开发票列表查询
path := "/v2/invoice/cy/zzsfpCy"
params := `{"cyList":[{"fpdm":"34******30","fphm":"17****68","kprq":"2021-11-01","je":1421.63}]}`
err = sendBusinessRequest(path, params)
if err!= nil {
fmt.Println("发送业务请求时出错:", err)
}
} // See https://aka.ms/new-console-template for more information
using System.Net.Http.Json;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
namespace Test{
class Program{
static void Main(String[] args){
Console.WriteLine("Hello, World!");
String appKey = "XXXXXXX";
String appSecret = "XXXXXXXXXXXX";
String accessToken = getAccessToken(appKey, appSecret);
Console.WriteLine("access_token: " + accessToken + "\r\n");
String body = "{\"cyList\":[{\"fpdm\": \"33002041**\",\"fphm\": \"011335**\",\"kprq\": \"2021-02-25\",\"je\": 11979.64}]}";
String fpcyRresult = fpcy(appKey, appSecret, accessToken, body);
Console.WriteLine("fpcyRresult: " + fpcyRresult);
}
static String getAccessToken(String appKey, String appSecret){
String clientSecret = getMD5(appSecret).ToLower();
//Console.WriteLine(clientSecret.Length + " " + clientSecret );
String url = "http://api.qixiangyun.com/v1/AGG/oauth2/login";
Dictionary<string, string> paras = new Dictionary<string, string>(){
{ "grant_type", "client_credentials"},
{ "client_appkey", appKey},
{ "client_secret", clientSecret}
};
String tokenJson = post(url, JsonSerializer.Serialize(paras));
Dictionary<string, Dictionary<string, object>> result = JsonSerializer.Deserialize<Dictionary<string, Dictionary<string, object>>>(tokenJson);
Dictionary<string, object> dic = result["value"];
//Console.WriteLine("access_token: " + dic["access_token"]);
return dic["access_token"].ToString();
}
static String fpcy(String appKey, String appSecret, String accessToken, String body){
long ts = new DateTimeOffset(DateTime.Now).ToUnixTimeMilliseconds();
String before = "POST" + "_" + getMD5(body).ToLower() + "_" + ts + "_" + accessToken + "_" + appSecret;
String after = "API-SV1:" + appKey + ":" + Convert.ToBase64String(Encoding.UTF8.GetBytes(getMD5(before).ToLower()));
Console.WriteLine("sign before: " + before);
Console.WriteLine("sign after: " + after + "\r\n");
String url = "http://api.qixiangyun.com/v1/FP/cy";
Dictionary<string, string> header = new Dictionary<string, string>(){
{ "access_token", accessToken},
{ "req_date", ts.ToString()},
{ "req_sign", after}
};
Dictionary<string, string> paras = new Dictionary<string, string>(){
};
String result = post(url, body, header);
return result;
}
static String post(String url, String jsonParas){
String responseBody = String.Empty;
using(HttpClient client = new HttpClient())
{
HttpContent httpContent = new StringContent(jsonParas);
httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
HttpResponseMessage response = client.PostAsync(url, httpContent).GetAwaiter().GetResult();
response.EnsureSuccessStatusCode();
responseBody = response.Content.ReadAsStringAsync().GetAwaiter().GetResult();
}
//Console.WriteLine(responseBody);
return responseBody;
}
static String post(String url, String jsonParas, Dictionary<String, String> dicHeader){
String responseBody = String.Empty;
using(HttpClient client = new HttpClient())
{
foreach(String kk in dicHeader.Keys){
client.DefaultRequestHeaders.Add(kk, dicHeader[kk]);
//Console.WriteLine(kk + ":" + dicHeader[kk]);
}
HttpContent httpContent = new StringContent(jsonParas);
httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
HttpResponseMessage response = client.PostAsync(url, httpContent).GetAwaiter().GetResult();
response.EnsureSuccessStatusCode();
responseBody = response.Content.ReadAsStringAsync().GetAwaiter().GetResult();
}
//Console.WriteLine(responseBody);
return responseBody;
}
static string getMD5(String str){
MD5 md5Hash = MD5.Create();
byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(str));
StringBuilder sBuilder = new StringBuilder();
for (int i = 0; i < data.Length; i++)
{
sBuilder.Append(data[i].ToString("x2"));
}
string hash = sBuilder.ToString();
return hash.ToUpper();
}
}
}