摘要:/** * curl -X POST 'http://127.0.0.1/v1/workflows/run' \ * --header 'Authorization: Bearer {api_key}' \ * --header 'Content-Type:
效果
测试代码
//参数定义是用的枚举:KEY+API地址 public void difyFlow(DifyReqType reqType) { OkHttpClient client= new OkHttpClient; Response response = null; try { //请求参数的封装 DifyReqBody form= new DifyReqBody; ObjectMapper objectMapper = new ObjectMapper; //json String json = objectMapper.writeValueAsString(form); System.out.println(json); requestBody body = RequestBody.create(json, MediaType.get("application/json; charset=utf-8")); Request.Builder builder = new Request.Builder .url(reqType.getReq_url) //认证部分 .addHeader("Authorization", "Bearer " + reqType.getApi_key) .addHeader("Content-Type", "application/json"); Request request = builder.post(body).build; Call call = client.newCall(request); response = call.execute; int code = response.code; /** * .toString :这将以字符串格式返回您的对象。 * .string :这将返回您的回复。 */ String responseBodyString = response.body.string; System.out.println(code+" 返回内容:"+responseBodyString); } catch (IOException e) { throw new RuntimeException(e); }finally { response.close; } }import requestsimport json#文件上传 主要得到上传后的ID(后面可以复用def upload_file(file_path, user): #这个是文件上传的API地址:http://127.0.0.1/v1/files/upload upload_url = "https://api.dify.ai/v1/files/upload" #认证信息再头文件里面 headers = { "Authorization": "Bearer app-xxxxxxxx", } try: print("上传文件中...") with open(file_path, 'rb') as file: //文件参数的key要对应你的输入参数名 files = { 'file': (file_path, file, 'text/plain') # 确保文件以适当的MIME类型上传 } #文件的一些信息 data = { "user": user, "type": "TXT"# 设置文件类型为TXT } response = requests.post(upload_url, headers=headers, files=files, data=data) if response.status_code == 201: # 201 表示创建成功 print("文件上传成功") return response.json.get("id") # 获取上传的文件 ID else: print(f"文件上传失败,状态码: {response.status_code}") return None except Exception as e: print(f"发生错误: {str(e)}") return None# 把上传的文件ID作为参数def run_workflow(file_id, user, response_mode="blocking"): # API地址 workflow_url = "https://api.dify.ai/v1/workflows/run" # 认证 headers = { "Authorization": "Bearer app-xxxxxxxxx", "Content-Type": "application/json" } #第一个调用的demo里面有提到 参数再ipputs里面 #type很重要 #这里面其实也可以是网络图片transfer_method:remote_url data = { "inputs": { "orig_mail": { "transfer_method": "local_file",#本地还是网络 "upload_file_id": file_id, #文件ID "type": "document"#类型 } }, "response_mode": response_mode, "user": user } try: print("运行工作流...") response = requests.post(workflow_url, headers=headers, json=data) if response.status_code == 200: print("工作流执行成功") return response.json else: print(f"工作流执行失败,状态码: {response.status_code}") return {"status": "error", "message": f"Failed to execute workflow, status code: {response.status_code}"} except Exception as e: print(f"发生错误: {str(e)}") return {"status": "error", "message": str(e)}# 使用示例file_path = "{your_file_path}"user = "difyuser"# 上传文件file_id = upload_file(file_path, user)if file_id: # 文件上传成功,继续运行工作流 result = run_workflow(file_id, user) print(result)else: print("文件上传失败,无法执行工作流")来源:正正杂说