JAVA调用方式

JAVA原生实现

package com.hisense.demo.utils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List; /**
* @author tianluhua
* @version 1.0
* @since 2024/11/13 17:49
*/
public class Demo {
public static void main(String[] args) {
String targetURL = "http://10.18.217.60:32641/film_grain_analysis"; // 替换为目标URL
File[] files = {
new File("D:\\desktop\\sample_img.jpg"), // 替换为第一个文件路径
new File("D:\\desktop\\sample_img_1.jpg") // 替换为第二个文件路径
};
String deviceId = "wfureufeewe"; // 替换为实际的deviceid try {
uploadFiles(targetURL, files, deviceId);
} catch (IOException e) {
e.printStackTrace();
}
} public static void uploadFiles(String targetURL, File[] files, String deviceId) throws IOException {
String boundary = "===" + System.currentTimeMillis() + "===";
String LINE_FEED = "\r\n"; URL url = new URL(targetURL);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
httpConn.setUseCaches(false);
httpConn.setDoOutput(true);
// 请求超时时间
httpConn.setReadTimeout(60 * 1000);
// 连接超时时间
httpConn.setConnectTimeout(10 * 1000);
httpConn.setDoInput(true);
httpConn.setRequestMethod("POST");
httpConn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); try (DataOutputStream request = new DataOutputStream(httpConn.getOutputStream())) {
// Add deviceid part
request.writeBytes("--" + boundary + LINE_FEED);
request.writeBytes("Content-Disposition: form-data; name=\"deviceid\"" + LINE_FEED);
request.writeBytes(LINE_FEED);
request.writeBytes(deviceId + LINE_FEED); // Add file parts
for (File file : files) {
String fileName = file.getName();
request.writeBytes("--" + boundary + LINE_FEED);
request.writeBytes("Content-Disposition: form-data; name=\"files\"; filename=\"" + fileName + "\"" + LINE_FEED);
request.writeBytes("Content-Type: " + HttpURLConnection.guessContentTypeFromName(fileName) + LINE_FEED);
request.writeBytes(LINE_FEED); try (FileInputStream inputStream = new FileInputStream(file)) {
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
request.write(buffer, 0, bytesRead);
}
}
request.writeBytes(LINE_FEED);
} // End of multipart/form-data.
request.writeBytes("--" + boundary + "--" + LINE_FEED);
request.flush();
} // Check server's response
int responseCode = httpConn.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
StringBuilder response = new StringBuilder(); try (BufferedReader in = new BufferedReader(new InputStreamReader(
httpConn.getInputStream()))) {
String inputLine;
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
}
String responseStr = response.toString();
System.out.println(responseStr);
} else {
System.out.println("File upload failed. Server returned HTTP code: " + responseCode);
}
} }

OKHttp实现

package com.hisense.demo.mobileagent;

import okhttp3.*;

import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit; /**
* @author tianluhua
* @version 1.0
* @since 2024/7/25 14:33
*/
public class Demo { /**
* 对应的 POST 请求接口,采用 form-data传参
*
*/
public static void main(String[] args) throws IOException { // 定义的接口API
String api = ""
OkHttpClient client = new OkHttpClient().newBuilder()
.connectTimeout(600, TimeUnit.SECONDS)
.writeTimeout(600, TimeUnit.SECONDS)
.readTimeout(600, TimeUnit.SECONDS)
.build();
MediaType mediaType = MediaType.parse("text/plain"); // 请求参数,可能有多个
RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)
// 文件参数,参数名为file,根据具体的接口协议来确定,文件的路径根据实际来确定
.addFormDataPart("file", "img.png",
RequestBody.create(MediaType.parse("application/octet-stream"), new File("E:\\work\\common\\coding\\java-demo\\src\\main\\java\\com\\hisense\\demo\\mobileagent\\img.png")))
// 其他参数
.addFormDataPart("instruction","hello")
// 其他参数
.addFormDataPart("knowledge","hello")
.build();
Request request = new Request.Builder()
.url(api)
.method("POST", body)
.build();
Response response = client.newCall(request).execute(); // 返回响应结果
System.out.println(response);
// 返回结果数据
String json = response.body().string();
}
}

Openfeign实现

  • fallbackFactory为反馈机制,也可以为空,采用默认的方式
@Component
@FeignClient(value = "test", contextId = "test", url = "${test.api}", fallbackFactory = TestApiFallbackFactory.class)
public interface TestApi { @PostMapping(value = "/generate", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
String generate(@RequestPart(value = "file") MultipartFile file, @RequestParam(value = "param") String param); }

Python调用方式

Requests库

import requests

url = "http://10.18.217.60:32641/film_grain_analysis"

payload = {'deviceid': '111212111'}
files=[('files',('sample_img.jpg',open('D:\\desktop\\sample_img.jpg','rb'),'image/jpeg')),
('files',('sample_img.jpg',open('D:\\desktop\\sample_img.jpg','rb'),'image/jpeg'))
]
headers = {} response = requests.request("POST", url, headers=headers, data=payload, files=files) print(response.text)

FormData接口调用的更多相关文章

  1. HttpClient远程接口调用-实名认证

    1.HttpClient远程接口调用 1)用户注册 注册按钮button提交表单时,要return false form表单 <!-- action="http://localhost ...

  2. node.js 接口调用示例

    测试用例git地址(node.js部分):https://github.com/wuyongxian20/node-api.git 项目架构如下: controllers: 文件夹下为接口文件 log ...

  3. 《C#微信开发系列(3)-获取接口调用凭据》

    3.0获取接口调用凭据 ①接口说明 access_token是公众号的全局唯一票据,公众号调用各接口时都需使用access_token.开发者需要进行妥善保存.access_token的存储至少要保留 ...

  4. asp.net mvc短信接口调用——阿里大于API开发心得

    互联网上有许多公司提供短信接口服务,诸如网易云信.阿里大于等等.我在自己项目里需要使用到短信服务起到通知作用,实际开发周期三天,完成配置.开发和使用,总的说,阿里大于提供的接口易于开发,非常的方便,短 ...

  5. PHP 使用 curl_* 系列函数和 curl_multi_* 系列函数进行多接口调用时的性能对比

    在页面中调用的服务较多时,使用并行方式,即使用 curl_multi_* 系列函数耗时要小于 curl_* 系列函数. 测试环境 操作系统:Windows x64 Server:Apache PHP: ...

  6. Spring AOP在函数接口调用性能分析及其日志处理方面的应用

    面向切面编程可以实现在不修改原来代码的情况下,增加我们所需的业务处理逻辑,比如:添加日志.本文AOP实例是基于Aspect Around注解实现的,我们需要在调用API函数的时候,统计函数调用的具体信 ...

  7. 基于JAVA的全国天气预报接口调用示例

    step1:选择本文所示例的接口"全国天气预报接口" url:https://www.juhe.cn/docs/api/id/39/aid/87step2:每个接口都需要传入一个参 ...

  8. bugzilla4的xmlrpc接口api调用实现分享: xmlrpc + https + cookies + httpclient +bugzilla + java实现加密通信下的xmlrpc接口调用并解决登陆保持会话功能

    xmlrpc .  https . cookies . httpclient.bugzilla . java实现加密通信下的xmlrpc接口调用并解决登陆保持会话功能,网上针对bugzilla的实现很 ...

  9. Spring框架下的 “接口调用、MVC请求” 调用参数、返回值、耗时信息输出

    主要拦截前端或后天的请求,打印请求方法参数.返回值.耗时.异常的日志.方便开发调试,能很快定位到问题出现在哪个方法中. 前端请求拦截,mvc的拦截器 import java.util.Date; im ...

  10. 云极知客开放平台接口调用方法(C#)

    云极知客为企业提供基于SAAS的智能问答服务.支持企业个性化知识库的快速导入,借助语义模型的理解和分析,使企业客户立即就拥有本行业的24小时客服小专家.其SAAS模式实现零成本投入下的实时客服数据的可 ...

随机推荐

  1. 几行代码带你用TinyEngine低代码引擎开发侧边栏插件

    本文分享自华为云社区<实操上手TinyEngine低代码引擎插件化开发>,作者:OpenTiny. 1.背景介绍 1.1 TinyEngine 低代码引擎简介 低代码开发是近些年非常热门的 ...

  2. 手写js new,new的过程到底发生了什么

    在JavaScript中,new关键字的应用可以说是再平常不过了,最基础的有new Array().new Set(),再而就是new一个自己创建的构造函数,也就是创建一个该构造函数的示例.如:var ...

  3. DashText-快速开始

    快速开始 DashText,是向量检索服务DashVector推荐使用的稀疏向量编码器(Sparse Vector Encoder),DashText可通过BM25算法将原始文本转换为稀疏向量(Spa ...

  4. ESP8266 + L298N

    L298N 知乎教程 L298N ESP8266 + L298N 连线 电机转的方向 电源引脚 VCC 外接直流电源引脚,电压范围在5~35V之间 GND GND是接地引脚,连接到电源负极 5V 驱动 ...

  5. 解决MobaXterm自动断开连接,亲测有效~

    场景: 使用MobaXterm工具通过SSH连接Linux服务器,如果一段时间没有操作,MobaXterm会把连接自动断开,这个设定很是不方便.通过更改下面的设置可以使SSH保持长连接,不会自动断开.

  6. 一篇讲透:模组典型上网业务的AT上网流程

    ​ 今天我们学习合宙模组典型上网业务的AT上网流程. 文末阅读原文,下载最新教程/固件. 一.简介 本文介绍了合宙4G模组的常用的AT指令和服务器交互的流程. 进一步详细的流程,参见各个模组的AT命令 ...

  7. JBOSS漏洞复现

    Jboss漏洞复现 统一靶场:/vulhub/jboss JMX Console 未授权访问漏洞 # 介绍 JBoss的webUI界面 http://ip:port/jmx-console未授权访问( ...

  8. 100 款支持 .NET 多版本的强大 WPF 控件库

    前言 推荐一款集成了超过100款控件的流行 XAML 控件库,同时提供了一系列常用的 .NET 帮助类-CookPopularUI.它可以简化开发流程,让我们能够更加专注于核心业务逻辑的实现. 让我们 ...

  9. Java网络爬虫的实现

    记得在刚找工作时,隔壁的一位同学在面试时豪言壮语曾实现过网络爬虫,当时的景仰之情犹如滔滔江水连绵不绝.后来,在做图片搜索时,需要大量的测试图片,因此萌生了从Amazon中爬取图书封面图片的想法,从网上 ...

  10. 编程辅助工具之Kite

    python作为一门门槛很低但又功能强大的编程语言,现在已经得到了非常广泛的使用,但是它的常用库非常多,而且往往更新后许多方法都有所变化,因此想要记住其大部分函数的用法对于大部分人来说比较困难,因而会 ...