无法接收 API 响应

我被困在如何将python代码转换为c#。我尝试了很多次但没有收到API响应。首先我尝试了这个

我的python代码


import sys

import base64

import requests

import json


file_path = 'limit.jpg'

image_uri = "data:image/jpg;base64," + base64.b64encode(open(file_path, "rb").read()).decode()

r = requests.post("https://api",

    data=json.dumps({'src': image_uri}),

    headers={"app_id": "YOUR_APP_ID", "app_key": "YOUR_APP_KEY",

             "Content-type": "application/json"})

print(json.dumps(json.loads(r.text), indent=4, sort_keys=True))

第一次尝试


using (var httpClient = new HttpClient())

        {

            using (var request = new HttpRequestMessage(new HttpMethod("POST"), "https://api."))

            {

                request.Headers.TryAddWithoutValidation("app_id", id);

                request.Headers.TryAddWithoutValidation("app_key",apiKey);


                request.Content = new StringContent("{ \"src\": \"data:image/jpeg;base64",PathToImage);

                request.Content.Headers.ContentType = new MediaTypeWithQualityHeaderValue("application/json");

                var response =  httpClient.SendAsync(request).Result;

                Console.WriteLine(    await response.Content.ReadAsStringAsync());


            }

        }

但是这里没有运气 API 响应是 {"error":"SyntaxError: Unexpected end of JSON input","error_info":{"id":"json_syntax","message":"SyntaxError: Unexpected end of JSON input"}} 我也尝试转换 cURL -


curl -X POST https://api \

-H 'app_id: YOUR_APP_ID' \

-H 'app_key: YOUR_APP_KEY' \

-H 'Content-Type: application/json' \

--data '{ "src": "data:image/jpeg;base64,'$(base64 -i limit.jpg)'" }'

但又没有运气了。也许我对图像中的 convertbase64 有误。


神不在的星期二
浏览 139回答 2
2回答

慕仙森

Python 代码不连接字符串。它的作用是:加载文件的内容,使用 Base64 对它们进行编码从 Base64 字符串创建图像 uri创建一个字典,其键为src图像 URI 并为其赋值。该字典被序列化为 JSON。json 字符串发布到 APIC# 中完全相同的步骤是:var data=File.ReadAllBytes(PathToImage);var base64=Convert.ToBase64(data);var imageUri="data:image/jpg;base64," + base64;var json=JsonConvert.SerializeObject(new {src=imageUri});var content=new StringContent(json,Encoding.UTF8,"application/json");await _client.PostAsync(apiUrl,content);这些调用可以合并,但最好先从干净的代码开始,然后再尝试缩短它。与 Python 的一个区别是这里创建了一个匿名对象,new {src=imageUri}而不是字典HttpClient 实例是线程安全的,旨在被重用,而不是被丢弃。API 密钥可以在创建 HttpClient 实例时设置一次,例如:_client.DefaultRequestHeaders.TryAddWithoutValidation("app_id", id);_client.DefaultRequestHeaders.TryAddWithoutValidation("app_key",apiKey);

波斯汪

我注意到您正在传递 PathToImage (我相信它具有图像文件的物理路径)而不是 base64 编码的图像内容。请在下面尝试:编辑代码:request.Content = new StringContent("{ \"src\": \"data:image/jpeg;base64,",Convert.ToBase64(System.IO.File.ReadAllBytes(PathToImage)),"\" }");如下几个语法更正 => base64 后缺少逗号。(我现在添加了)最后,您必须指定 "\" }" 关闭带有结束引号的大括号以标记 json 对象的结尾
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python