用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 素材场景中光线烘焙后灯光失效
- ¥15 请教一下各位,为什么我这个没有实现模拟点击
- ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
- ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
- ¥20 有关区间dp的问题求解
- ¥15 多电路系统共用电源的串扰问题
- ¥15 slam rangenet++配置
- ¥15 有没有研究水声通信方面的帮我改俩matlab代码
- ¥15 ubuntu子系统密码忘记
- ¥15 保护模式-系统加载-段寄存器