java上传附件的接口_蓝信上传附件接口调用(JAVA)

该代码段展示了如何使用Java进行蓝信附件上传的接口调用。通过设置HTTP请求参数、构造multipart/form-data格式的数据并发送POST请求,实现文件上传到蓝信平台。
摘要由CSDN通过智能技术生成

/*** 上传蓝信附件

*@paramaccessToken

*@paramfilename

*@return

*/

publicJSONObject uploadMedia(String accessToken,String filename) {

JSONObject jsonObject= null;

String UPLOAD_WECHAT_URL= "https://login.lanxin.cn/cgi-bin/media/upload?access_token=ACCESS_TOKEN&type=TYPE";

String last_lanx_url= UPLOAD_WECHAT_URL.replace("ACCESS_TOKEN", accessToken);//定义数据分割符

String boundary = "----------sunlight";//

try{

File file=newFile(filename);//URL url = new URL(last_lanx_url);

URL url = new URL(null,last_lanx_url,newsun.net.www.protocol.https.Handler());

HttpsURLConnection conn=(HttpsURLConnection) url.openConnection();//发送POST请求必须设置如下两行

conn.setDoOutput(true);

conn.setDoInput(true);

conn.setUseCaches(false);

conn.setRequestMethod("POST");

conn.setRequestProperty("connection", "Keep-Alive");

conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");

conn.setRequestProperty("Charsert", "UTF-8");

conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" +boundary);

OutputStream out= newDataOutputStream(conn.getOutputStream());byte[] end_data = ("\r\n--" + boundary + "--\r\n").getBytes();//定义最后数据分隔线

StringBuilder sb = newStringBuilder();

sb.append("--");

sb.append(boundary);

sb.append("\r\n");

sb.append("Content-Disposition: form-data;name=\"media\";filename=\"" + file.getName() + "\"\r\n");

sb.append("Content-Type:application/octet-stream\r\n\r\n");byte[] data =sb.toString().getBytes();

out.write(data);

DataInputStream in= new DataInputStream(newFileInputStream(file));int bytes = 0;byte[] bufferOut = new byte[1024 * 8];while ((bytes = in.read(bufferOut)) != -1) {

out.write(bufferOut,0, bytes);

}

out.write("\r\n".getBytes()); //多个文件时,二个文件之间加入这个

in.close();

out.write(end_data);

out.flush();

out.close();//定义BufferedReader输入流来读取URL的响应

BufferedReader reader = new BufferedReader(newInputStreamReader(conn.getInputStream()));

String line= null;

StringBuffer buffer= newStringBuffer();while ((line = reader.readLine()) != null) {

buffer.append(line);

}

System.out.println("请求蓝信上传附件接口响应报文内容为:"+buffer.toString());

jsonObject=JSONObject.parseObject(buffer.toString());

}catch(Exception e) {

System.out.println("POST请求蓝信上传附件接口出现异常");

e.printStackTrace();return null;

}returnjsonObject;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值