Java 微信企业号上传文件 java 代码
时间: 2023-08-01 10:07:44 浏览: 104
好的,以下是 Java 微信企业号上传文件的示例代码:
```java
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
public class WechatMediaUpload {
/**
* 上传文件到微信服务器
*
* @param accessToken 微信企业号的 access_token
* @param fileType 文件类型,可选值为image、voice、video、file
* @param file 要上传的文件
* @throws Exception
*/
public static String uploadFile(String accessToken, String fileType, File file) throws Exception {
String url = "https://qyapi.weixin.qq.com/cgi-bin/media/upload?type=" + fileType + "&access_token=" + accessToken;
URL urlObj = new URL(url);
HttpURLConnection conn = (HttpURLConnection) urlObj.openConnection();
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
String boundary = "-----------------------------" + System.currentTimeMillis();
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
OutputStream out = new DataOutputStream(conn.getOutputStream());
// 文件部分
StringBuilder sb = new StringBuilder();
sb.append("--").append(boundary).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");
out.write(sb.toString().getBytes());
DataInputStream in = new DataInputStream(new FileInputStream(file));
int bytes = 0;
byte[] bufferOut = new byte[1024];
while ((bytes = in.read(bufferOut)) != -1) {
out.write(bufferOut, 0, bytes);
}
in.close();
out.write(("\r\n--" + boundary + "--\r\n").getBytes());
out.flush();
out.close();
// 读取返回数据
StringBuffer buffer = new StringBuffer();
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
String line = null;
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (reader != null) {
reader.close();
}
}
conn.disconnect();
return buffer.toString();
}
public static void main(String[] args) {
try {
String accessToken = "your_access_token";
String fileType = "image"; // 上传文件类型,可选值为image、voice、video、file
File file = new File("your_file_path");
String result = uploadFile(accessToken, fileType, file);
System.out.println(result);
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
注意替换代码中的 access_token 和文件路径,以及设置正确的文件类型。文件类型为企业号 API 中定义的四种类型之一:image、voice、video 和 file。
阅读全文