http://www.sufeinet.com/plugin.php?id=keke_group

苏飞论坛

 找回密码
 马上注册

QQ登录

只需一步,快速开始

分布式系统框架(V2.0) 轻松承载百亿数据,千万流量!讨论专区 - 源码下载 - 官方教程

HttpHelper爬虫框架(V2.7-含.netcore) HttpHelper官方出品,爬虫框架讨论区 - 源码下载 - 在线测试和代码生成

HttpHelper爬虫类(V2.0) 开源的爬虫类,支持多种模式和属性 源码 - 代码生成器 - 讨论区 - 教程- 例子

查看: 89880|回复: 0

[学生提问] 求助c# API请求 无反应

[复制链接]
发表于 2024-3-18 12:48:42 | 显示全部楼层 |阅读模式
69金钱
愣是不知道哪里出问题,点击没反应。。。ApiSDK https://help.aliyun.com/zh/dashs ... ebsiteRedirect=true

微信截图_20240318124651.png


[C#] 纯文本查看 复制代码
using System;
using System.IO;
using System.Net.Http;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Threading.Tasks;
using System.Text;

namespace ty
{
    public partial class Form1 : Form
    {
        private readonly HttpClient httpClient = new HttpClient();
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void button1_Click_1(object sender, EventArgs e)
        {
            // 获取textBox2中的目录路径
            string directoryPath = textBox2.Text;

            // 检查目录是否存在并删除小于1KB的TXT文件
            ProcessDirectory(directoryPath, 1024, "已经删除小于 1KB 的 TXT.");
        }

        private void button2_Click_1(object sender, EventArgs e)
        {
            // 获取textBox2中的目录路径
            string directoryPath = textBox2.Text;

            // 检查目录是否存在并删除大于5KB的TXT文件
            ProcessDirectory(directoryPath, 5120, "已经删除大于 5KB 的 TXT.");
        }
        private void button3_Click(object sender, EventArgs e)
        {
             
        }

        private async void button4_Click(object sender, EventArgs e)
        {
            // 点击后更改button4文本
            button4.Text = "正在改写文章中";
            button4.Enabled = false;

            // 禁用其他按钮
            button1.Enabled = false;
            button2.Enabled = false;
            button3.Enabled = false;

            string apiKey = textBox1.Text.Trim();
            string directoryPath = textBox2.Text;
            string iniFilename = "zhiling.ini";

            if (!Directory.Exists(directoryPath))
            {
                textBox3.AppendText("当前目录不存在,请重新检查路径!." + Environment.NewLine);
                return;
            }

            string outputDirectory = Path.Combine(directoryPath, "已改写");
            if (!Directory.Exists(outputDirectory))
            {
                Directory.CreateDirectory(outputDirectory);
            }

            var txtFiles = Directory.GetFiles(directoryPath, "*.txt");

            List<Task> tasks = new List<Task>();
            foreach (var txtFile in txtFiles)
            {
                string content = File.ReadAllText(txtFile, Encoding.UTF8);


                string iniContent = ReadIniContent(Path.Combine(directoryPath, iniFilename));
                if (iniContent != null)
                {
                    string appendedContent = content + "\n" + iniContent;
                    tasks.Add(ProcessFileAsync(appendedContent, "qwen-turbo", apiKey, txtFile, outputDirectory));

                }
                else
                {
                    textBox3.AppendText($"无法读取INI文件内容: {iniFilename}{Environment.NewLine}");
                    return;
                }



            }

            // 等待所有文件处理完成
            await Task.WhenAll(tasks);

            // 所有文件处理完毕后恢复按钮状态
            button4.Text = "改写文章内容";
            button4.Enabled = true;

            // 启用其他按钮
            button1.Enabled = true;
            button2.Enabled = true;
            button3.Enabled = true;
        }



        private async Task ProcessFileAsync(string appendedContent, string model, string apiKey, string txtFile, string outputDirectory)
        {

            try
            {
                HttpResponseMessage response = await CallApiAsync(appendedContent, model, apiKey);
                if (response != null && response.IsSuccessStatusCode)
                {
                    string responseJson = await response.Content.ReadAsStringAsync();
                    
                        var result = JsonConvert.DeserializeObject<Dictionary<string, object>>(responseJson);
                    dynamic responseJsonDynamic = JsonConvert.DeserializeObject<dynamic>(responseJson);

                    if (responseJson != null)
                    {
                        string outputText = responseJsonDynamic.output.text;
                        // 在这里添加对outputText的空值检查
                        if (!string.IsNullOrEmpty(outputText))
                        {
                            string newFilename = Path.GetFileNameWithoutExtension(txtFile) + ".txt";
                            string outputPath = Path.Combine(outputDirectory, newFilename);

                            File.WriteAllText(outputPath, outputText, Encoding.UTF8);

                            File.Delete(txtFile);
                        }
                        else
                        {
                            textBox3.Invoke((MethodInvoker)(() =>
                            {
                                textBox3.AppendText($"无法从API响应中获取有效内容.{Environment.NewLine}");
                            }));
                        }
                    }
                    else
                    {
                        textBox3.Invoke((MethodInvoker)(() =>
                        {
                            textBox3.AppendText($"调用API时发生错误,状态码: {response?.StatusCode}{Environment.NewLine}");
                        }));
                    }
                }
            }
            catch (Exception ex)
            {
                textBox3.Invoke((MethodInvoker)(() =>
                {
                    textBox3.AppendText($"在处理文件 {txtFile} 时发生错误:{ex.Message}{Environment.NewLine}");
                }));
            }
        }

        private void ProcessDirectory(string directoryPath, int sizeThreshold, string message)
        {
            try
            {
                string[] txtFiles = Directory.GetFiles(directoryPath, "*.txt");

                foreach (string filePath in txtFiles)
                {
                    long fileSize = new FileInfo(filePath).Length;

                    if (sizeThreshold < 0 ? fileSize <= -sizeThreshold : fileSize >= sizeThreshold)
                    {
                        File.Delete(filePath);
                        textBox3.AppendText($"{filePath}{Environment.NewLine}");
                    }
                }

                textBox3.AppendText(message + Environment.NewLine);
            }
            catch (Exception ex)
            {
                textBox3.AppendText($"An error occurred: {ex.Message}{Environment.NewLine}");
            }
        }

        private string ReadIniContent(string filename)
        {
            if (File.Exists(filename))
            {
                using (StreamReader reader = new StreamReader(filename, Encoding.UTF8))
                {
                    return reader.ReadToEnd();
                }
            }
            else
            {
                throw new FileNotFoundException("指定的 INI 文件未找到");
            }
        }

        private async Task<HttpResponseMessage> CallApiAsync(string prompt, string model, string apiKey)
        {
            var url = "https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation";
            var headers = new Dictionary<string, string>
            {
                { "Content-Type", "application/json" },
                { "Authorization", $"Bearer {apiKey}" },
            };

            var body = new Dictionary<string, object>
            {
                { "model", model },
                { "input", new Dictionary<string, string> { { "prompt", prompt } } },
                { "parameters", new Dictionary<string, int> { { "max_tokens", 1500 } } },
            };

            var jsonBody = JsonConvert.SerializeObject(body);
            var httpContent = new StringContent(jsonBody, Encoding.UTF8, "application/json");

            return await httpClient.PostAsync(url, httpContent);
        }
    }
}




1. 开通SVIP会员,免费下载本站所有源码,不限次数据,不限时间
2. 加官方QQ群,加官方微信群获取更多资源和帮助
3. 找站长苏飞做网站、商城、CRM、小程序、App、爬虫相关、项目外包等点这里
您需要登录后才可以回帖 登录 | 马上注册

本版积分规则

QQ|手机版|小黑屋|手机版|联系我们|关于我们|广告合作|苏飞论坛 ( 豫ICP备18043678号-2)

GMT+8, 2024-12-22 09:11

© 2014-2021

快速回复 返回顶部 返回列表