java使用httpclient调用上传图片接口[示例] -凯发k8官方网
凯发k8官方网
收集整理的这篇文章主要介绍了
java使用httpclient调用上传图片接口[示例]
小编觉得挺不错的,现在分享给大家,帮大家做个参考.
参考网站:nodejs使用http模块编写上传图片接口测试客户端
如果是java控制台app可以前往http://hc.apache.org/downloads.cgi下载新版httpclient库
示例调用上传图片接口代码示例:
import org.apache.http.consts; import org.apache.http.httpentity; import org.apache.http.httpresponse; import org.apache.http.namevaluepair; import org.apache.http.client.methods.httppost; import org.apache.http.entity.contenttype; import org.apache.http.entity.mime.multipartentitybuilder; import org.apache.http.entity.mime.content.filebody; import org.apache.http.impl.client.closeablehttpclient; import org.apache.http.impl.client.httpclients; import org.apache.http.message.basicnamevaluepair; import org.apache.http.util.entityutils;import java.io.file; import java.io.ioexception; import java.nio.charset.charset; import java.util.arraylist; import java.util.list;public class main {public static void main(string[] args) {closeablehttpclient httpclient = httpclients.createdefault();httppost httppost = new httppost("http://127.0.0.1:5000/");//建立httppost对象,改成自己的地址file file = new file("c:\\temp.png");//相对路径使用不了的话,使用图片绝对路径if(!file.exists()){//判断文件是否存在system.out.print("文件不存在");return;}filebody bin = new filebody(file, contenttype.create("image/png", consts.utf_8));//创建图片提交主体信息httpentity entity = multipartentitybuilder.create().setcharset(charset.forname("utf-8")).addpart("file", bin)//添加到请求.build();httppost.setentity(entity);httpresponse response= null;//发送post,并返回一个httpresponse对象try {response = httpclient.execute(httppost);if(response.getstatusline().getstatuscode()==200) {//如果状态码为200,就是正常返回string result = entityutils.tostring(response.getentity());system.out.print(result);}} catch (ioexception e) {e.printstacktrace();}system.out.print(response);system.out.print("结束");} }总结
以上是凯发k8官方网为你收集整理的java使用httpclient调用上传图片接口[示例]的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇: python3 随机数 质数 素数 文
- 下一篇: c stl学习之容器set和mult