项目需要对接外部接口,将图片文件流发送到外部接口,下面代码就是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;