HttpsURLConnection上传文件流(实例讲解)
程序员文章站
2023-12-14 19:26:22
项目需要对接外部接口,将图片文件流发送到外部接口,下面代码就是httpsurlconnection如何上传文件流:
/**
* httpsurlconne...
项目需要对接外部接口,将图片文件流发送到外部接口,下面代码就是httpsurlconnection如何上传文件流:
/** * httpsurlconnection上传文件流 * * @param args * @throws exception */ public static void main(string[] args) throws exception { //本地图片 java.io.file file = new java.io.file("/users/jikukalun/pictures/id1.jpg"); fileinputstream fileinputstream = new fileinputstream(file); //对接外部接口 string urlstring = "************"; url url = new url(urlstring); httpsurlconnection con = (httpsurlconnection) url.openconnection(); // 设置是否向httpurlconnection输出,因为这个是post请求,参数要放在 // http正文内,因此需要设为true, 默认情况下是false; con.setdooutput(true); // 设置是否从httpurlconnection读入,默认情况下是true; con.setdoinput(true); // 设定请求的方法为"post",默认是get con.setrequestmethod("post"); // post 请求不能使用缓存 con.setusecaches(false); // 设定传送的内容类型是可序列化的java对象 // (如果不设此项,在传送序列化对象时,当web服务默认的不是这种类型时可能抛java.io.eofexception) // con.setrequestproperty("content-type", "application/x-java-serialized-object"); outputstream out = con.getoutputstream(); //读取本地图片文件流 fileinputstream inputstream = new fileinputstream(file); byte[] data = new byte[2048]; int len = 0; int sum = 0; while ((len = inputstream.read(data)) != -1) { //将读取到的本地文件流读取到httpsurlconnection,进行上传 out.write(data, 0, len); sum = len + sum; } system.out.println("上传图片大小为:" + sum); out.flush(); inputstream.close(); out.close(); int code = con.getresponsecode(); //获取post请求返回状态 system.out.println("code=" + code + " url=" + url); if (code == 200) { inputstream inputstream2 = con.getinputstream(); bytearrayoutputstream bos = new bytearrayoutputstream(); while ((len = inputstream2.read(data)) != -1) { bos.write(data, 0, len); } inputstream2.close(); string content = bos.tostring(); bos.close(); system.out.println("result =" + content); //将返回的json格式的字符串转化为json对象 jsonobject json = jsonobject.parseobject(content); try { system.out.println("name=" + json.getstring("name") + ", people=" + json.getstring("people") + ", sex=" + json.getstring("sex") + ", id_number=" + json.getstring("id_number") + ", type=" + json.getstring("type") + ", address=" + json.getstring("address") + ", birthday=" + json.getstring("birthday")); } catch (jsonexception e) { e.printstacktrace(); } } //断开httpsurlconnection连接 con.disconnect(); }
引用jar包:
import com.alibaba.fastjson.jsonexception; import com.alibaba.fastjson.jsonobject; import javax.net.ssl.httpsurlconnection; import java.io.*; import java.net.httpurlconnection; import java.net.malformedurlexception; import java.net.url;
以上这篇httpsurlconnection上传文件流(实例讲解)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。