用c#代码实现将本地文件上传到百度文库 有研究过这个的吗 希望能帮助下 谢谢
1条回答
- Olin_ଲ 2023-03-06 13:16关注
import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; public class BaiduWenkuUploader { private static final String UPLOAD_API_URL = "https://wenku.baidu.com/api/upload"; public static void uploadFile(String filePath) throws IOException { File file = new File(filePath); String fileName = file.getName(); // 创建HTTP连接 URL url = new URL(UPLOAD_API_URL); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setRequestMethod("POST"); conn.setRequestProperty("User-Agent", "Mozilla/5.0"); conn.setRequestProperty("Referer", "https://wenku.baidu.com/"); // 设置请求正文 InputStream inputStream = new FileInputStream(file); byte[] fileBytes = inputStream.readAllBytes(); String boundary = "------------------------" + Long.toHexString(System.currentTimeMillis()); conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); conn.setRequestProperty("Content-Length", Integer.toString(fileBytes.length)); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("Cache-Control", "no-cache"); // 构造请求正文 String prefix = "--" + boundary + "\r\nContent-Disposition: form-data; name=\"file\"; filename=\"" + fileName + "\"\r\n\r\n"; String suffix = "\r\n--" + boundary + "--\r\n"; byte[] prefixBytes = prefix.getBytes(); byte[] suffixBytes = suffix.getBytes(); byte[] contentBytes = new byte[fileBytes.length + prefixBytes.length + suffixBytes.length]; System.arraycopy(prefixBytes, 0, contentBytes, 0, prefixBytes.length); System.arraycopy(fileBytes, 0, contentBytes, prefixBytes.length, fileBytes.length); System.arraycopy(suffixBytes, 0, contentBytes, prefixBytes.length + fileBytes.length, suffixBytes.length); // 发送请求 conn.getOutputStream().write(contentBytes); // 处理响应 int responseCode = conn.getResponseCode(); String responseBody = conn.getResponseMessage(); if (responseCode == HttpURLConnection.HTTP_OK) { System.out.println("文件上传成功!"); } else { System.out.println("文件上传失败:" + responseBody); } } }
解决 无用评论 打赏 举报
悬赏问题
- ¥15 三菱伺服电机按启动按钮有使能但不动作
- ¥20 为什么我写出来的绘图程序是这样的,有没有lao哥改一下
- ¥15 js,页面2返回页面1时定位进入的设备
- ¥200 关于#c++#的问题,请各位专家解答!网站的邀请码
- ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
- ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
- ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
- ¥20 腾讯企业邮箱邮件可以恢复么
- ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
- ¥15 错误 LNK2001 无法解析的外部符号