You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过HttpURLConnection利用OutputStreamWriter上传InputStream内容

解决方法

你需要将InputStream中的内容通过字符流读取后,写入OutputStreamWriter完成上传。可以借助缓冲流提升效率,同时要做好流的资源管理和异常处理。

修改后的完整代码示例

String uURL = "http://some_domain/add";
URL url = new URL(uURL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
// 上传JSON文件的话,Content-Type设为application/json更规范,text/plain也可兼容
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestMethod("PUT");

// 使用try-with-resources自动管理流资源
try (OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), StandardCharsets.UTF_8);
     BufferedReader reader = new BufferedReader(new InputStreamReader(iStream, StandardCharsets.UTF_8))) {

    String line;
    // 逐行读取输入流内容并写入输出流
    while ((line = reader.readLine()) != null) {
        out.write(line);
        out.write(System.lineSeparator()); // 保留换行符,避免内容格式错乱
    }
    out.flush(); // 确保所有内容都发送至服务器

    // 校验服务器响应状态
    int responseCode = connection.getResponseCode();
    if (responseCode == HttpURLConnection.HTTP_OK) {
        System.out.println("文件上传成功");
    } else {
        System.out.println("上传失败,响应码:" + responseCode);
    }
} catch (IOException e) {
    e.printStackTrace();
} finally {
    connection.disconnect(); // 断开连接释放资源
}

关键注意点

  • 明确指定字符编码(如UTF_8),避免不同环境下出现编码乱码问题。
  • 如果上传的是二进制文件(图片、压缩包等),不要使用OutputStreamWriter,直接用字节流(OutputStream)传输,同时将Content-Type改为对应类型(如image/jpeg)或通用的application/octet-stream。
  • 若服务器要求用POST方法接收文件,将setRequestMethod("PUT")改为setRequestMethod("POST")即可。

内容的提问来源于stack exchange,提问作者Lara

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 00:39:58