Java 使用输入输出流发送与接收HTTP请求数据

Java 使用输入输出流发送与接收HTTP请求数据,第1张

Java 使用 输入输出流发送与接收HTTP请求数据

由于频繁萃取文件内容,服务器内存被字符串占满,所以使用流的方式处理,因为流一旦被关闭就会释放其占用的资源,而字符串要等着GC回收

请求方法
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import org.json.simple.JSONObject;

public class TestFile {

  private static final String URL = "http://127.0.0.1/file/getFileContent";

  public static void main(String[] args) throws IOException {
    String get = httpRequest(URL, "GET", new HashMap<>());
    System.err.println(get);
  }

  public static String httpRequest(String requestUrl, String requestMethod, Map<String, String> requestParameters) throws IOException {
    InputStream inputStream = null;
    InputStreamReader inputStreamReader = null;
    BufferedReader bufferedReader = null;
    try {
      URL url = new URL(requestUrl);
      HttpURLConnection conn = (HttpURLConnection) url.openConnection();
      conn.setDoOutput(true);//需要用到输出流
      conn.setDoInput(true);//需要用到输入流
      conn.setRequestMethod(requestMethod);
      conn.setRequestProperty("content-type", "text/html");//设置内容类型
      // 使用输出流添加数据至请求体
      if (requestParameters.size() != 0) {
        String json = JSONObject.toJSONString(requestParameters);
        OutputStream os = conn.getOutputStream();//获取输出流
        os.write(json.getBytes());//写入
        os.flush();
      }
      conn.connect();
      // 读取服务器端返回的内容
      inputStream = conn.getInputStream();
      inputStreamReader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
      bufferedReader = new BufferedReader(inputStreamReader);
      StringBuilder buffer = new StringBuilder();
      String line;
      while ((line = bufferedReader.readLine()) != null) {
        buffer.append(line);
      }
      return buffer.toString();
    } catch (Exception e) {
      e.printStackTrace();
      throw e;
    } finally {
      assert inputStream != null;
      inputStream.close();
      assert inputStreamReader != null;
      inputStreamReader.close();
      assert bufferedReader != null;
      bufferedReader.close();
    }
  }
}

返回内容
package com.demo.controller;

import com.alibaba.fastjson.JSONObject;
import com.demo.service.FileService;
import com.jfinal.aop.Inject;
import com.jfinal.core.Controller;
import com.jfinal.core.Path;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletResponse;
import jdk.nashorn.internal.parser.JSONParser;

/**
 * @author 16233
 */

@Path("/file")
public class FileController extends Controller {
 
  @Inject
  FileService fileService;

   @Clear
  public void getFileContentStream() throws Exception {
    ServletInputStream inputStream = getRequest().getInputStream();
    InputStreamReader inputStreamReader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
    BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
    try {
      StringBuilder buffer = new StringBuilder();
      String line;
      while ((line = bufferedReader.readLine()) != null) {
        buffer.append(line);
      }
      JSONObject jsonObject = JSONObject.parseObject(buffer.toString());

      File file = FS.getFile(jsonObject.getString("path").trim().replaceAll("\\", "/"));
      HttpServletResponse response = getResponse();
      InputStream fileContext;
      if (file == null || !file.exists()) {
        fileContentService.writeResponse(response, null, file);
      } else {
      // 获取文件内容的逻辑
        fileContext = fileContentService.getFileContentStream(file);
        fileContentService.writeResponse(response, fileContext, file);
      }
      renderNull();
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      inputStream.close();
      inputStreamReader.close();
      bufferedReader.close();
    }

  }

}



//  fileContentService.writeResponse(response, fileContext, file);
  public void writeResponse(HttpServletResponse response, InputStream fileContext, File file) throws IOException {
    OutputStream outputStream = null;
    if (fileContext == null) {
      fileContext = new ByteArrayInputStream("".getBytes());
    }
    try {
      response.setContentType("application/octet-stream");
      response.setHeader("Content-disposition", "attachment;filename=" + file.getName());
      outputStream = response.getOutputStream();
      byte[] bis = new byte[1024];
      while (-1 != fileContext.read(bis)) {
        outputStream.write(bis);
      }
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      fileContext.close();
      if (outputStream != null) {
        outputStream.flush();
        outputStream.close();
      }
    }
  }

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/794655.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-06
下一篇 2022-05-06

发表评论

登录后才能评论

评论列表(0条)

保存