@SneakyThrows
public static void main(String[] args) {
InputStream inputStream;
// 请求地址
String url = "http://api.note.youdao.com/group/file/create";
// okHttp:版本3.8.1
OkHttpClient okHttpClient = new OkHttpClient();
// 本地文件:注意关闭流
inputStream = new FileInputStream(new File("C:\\test.docx"));
RequestBody requestBody = new RequestBody() {
// 可以设置为空,也可以设置contentType:file.getContentType();
@Override
public okhttp3.MediaType contentType() {
return null;
}
// 传递文件流
@Override
public void writeTo(BufferedSink bufferedSink) throws IOException {
bufferedSink.writeAll(Okio.source(inputStream));
}
};
// 参数:
List<Pair<String, String>> params = Lists.newArrayList(
Pair.of("groupId", "123456"),
Pair.of("parentId", "-1"),
Pair.of("groupId", "test.docx"), // 需要填写文件后缀
Pair.of("fileSize", "345") // 文件大小值需要与上传文件大小保持一致
);
HttpUrl.Builder httpBuilder = Objects.requireNonNull(HttpUrl.parse(url)).newBuilder();
params.forEach(pair -> httpBuilder.addQueryParameter(pair.getKey(), pair.getValue()));
okhttp3.Request.Builder builder = (new okhttp3.Request.Builder())
.url(httpBuilder.build())
.post(requestBody)
.addHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
// execute
Response response = okHttpClient.newCall(builder.build()).execute();
}