gpt4 book ai didi

java - 如何使用 java 执行后调用

转载 作者:行者123 更新时间:2023-11-29 03:33:45 25 4
gpt4 key购买 nike

我正在使用下面的 html 来调用我的服务器 api(rest)之一

<html>

<body>
<form method="post" action="http://localhost:8080/service/uploadFile" enctype="multipart/form-data">
<input type="file" name="file"/>
<input type="submit"/>
<input type="hidden" name="smallSize" value="50x50">
</form>
</body>
</html>

如何使用 java 方法调用此 api?

最佳答案

以下几行可能对您有所帮助。我正在使用 Apache Http api。

HttpClient client = new DefaultHttpClient();
client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpPost post = new HttpPost( "http://localhost:8080/service/uploadFile"));
MultipartEntity entity = new MultipartEntity( HttpMultipartMode.BROWSER_COMPATIBLE );
StringBody size= new StringBody("50x50");
entity.addPart("smallSize", size);
entity.addPart("file", new FileBody(new File("D:/abc.txt") ));
post.setEntity(entity);

HttpResponse response = client.execute(post);
String responseFromServer = EntityUtils.toString(response.getEntity(), "UTF-8" );
client.getConnectionManager().shutdown();
System.out.println("response from server: "+responseFromServer);

其中 HttpPostHttpGet 类根据您的请求类型可用。为了发送文件,我们需要使用 MultipartEntity 类。如果您想像任何元数据一样将其他表单字段与 FileBody 一起发送,您可以使用 StringBody

希望对您有所帮助。 :)

关于java - 如何使用 java 执行后调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16604934/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com