java中的接口是类吗
472
2023-05-03
HttpsURLConnection上传文件流(实例讲解)
项目需要对接外部接口,将图片文件流发送到外部接口,下面代码就是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);
// 设MqmCbMJAT置是否从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"));
http:// } 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;
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~