Java Httpclient 文件上传与接收

Posted Java璐到底

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java Httpclient 文件上传与接收相关的知识,希望对你有一定的参考价值。

导入pom依赖

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.4</version>
</dependency>
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpmime</artifactId>
    <version>4.4</version>
</dependency>

上传代码:

    /**
     *
     * @param filepath 文件全路径
     * @param fileName  文件名
     * @return
     * @throws IOException
     */
    @PostMapping(value = "/upfileload.do")
    public String upfileload(String filepath,String fileName) throws IOException 
        System.out.println("传入参数------》" + filepath + "----" + fileName);
        DataInputStream in = null;
        OutputStream out = null;
        HttpURLConnection conn = null;
        JSONObject resposeTxt = null;
        InputStream ins = null;
        ByteArrayOutputStream outStream = null;
        try 
//            URL url = new URL("http://192.168.3.11:8081/mes-boot-doc/test/fileupload?fileName=shafei.xls");
            URL url = new URL("http://localhost:8009/fileupload?fileName="+fileName);

            conn = (HttpURLConnection) url.openConnection();
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setUseCaches(false);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "text/html");
            conn.setRequestProperty("Cache-Control", "no-cache");
            conn.setRequestProperty("Charsert", "UTF-8");
            conn.connect();
            conn.setConnectTimeout(10000);
            out = conn.getOutputStream();

            File file = new File(filepath);
            in = new DataInputStream(new FileInputStream(file));

            int bytes = 0;
            byte[] buffer = new byte[1024];
            while ((bytes = in.read(buffer)) != -1) 
                out.write(buffer, 0, bytes);
            
            out.flush();

            // 返回流
            if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) 
                ins = conn.getInputStream();
                outStream = new ByteArrayOutputStream();
                byte[] data = new byte[1024];
                int count = -1;
                while ((count = ins.read(data, 0, 1024)) != -1) 
                    outStream.write(data, 0, count);
                
                data = null;
                resposeTxt = JSONObject.parseObject(new String(outStream
                        .toByteArray(), "UTF-8"));
            
         catch (Exception e) 
            e.printStackTrace();
         finally 
            if (in != null) 
                in.close();
            
            if (out != null) 
                out.close();
            
            if (ins != null) 
                ins.close();
            
            if (outStream != null) 
                outStream.close();
            
            if (conn != null) 
                conn.disconnect();
            
        
        return  "SUCESS";
    

接收代码:

@PostMapping("/fileupload")
public String uploadFile(HttpServletRequest request,HttpServletResponse response) throws Exception
    String fileName = request.getParameter("fileName");
    System.out.println("filename:"+fileName);
    String fileFullPath = "C:/HWKJ/FTP/" + fileName;

    InputStream input = null;
    FileOutputStream fos = null;
    try 
        input = request.getInputStream();
        File file = new File("C:/HWKJ/FTP/");
        if(!file.exists())
            file.mkdirs();
        
        fos = new FileOutputStream(fileFullPath);
        int size = 0;
        byte[] buffer = new byte[1024];
        while ((size = input.read(buffer,0,1024)) != -1) 
            fos.write(buffer, 0, size);
        

        //响应信息 json字符串格式
        Map<String,Object> responseMap = new HashMap<String,Object>();
        responseMap.put("flag", true);

        //生成响应的json字符串
        String jsonResponse = JSONObject.toJSONString(responseMap);
        sendResponse(jsonResponse,response);
     catch (IOException e) 
        //响应信息 json字符串格式
        Map<String,Object> responseMap = new HashMap<String,Object>();
        responseMap.put("flag", false);
        responseMap.put("errorMsg", e.getMessage());
        String jsonResponse = JSONObject.toJSONString(responseMap);
        sendResponse(jsonResponse,response);
     finally
        if(input != null)
            input.close();
        
        if(fos != null)
            fos.close();
        
    

    return null;


/**
 * 返回响应
 *
 * @throws Exception
 */
private void sendResponse(String responseString,HttpServletResponse response) throws Exception 
    response.setContentType("application/json;charset=UTF-8");
    PrintWriter pw = null;
    try 
        pw = response.getWriter();
        pw.write(responseString);
        pw.flush();
     finally 
        IOUtils.closeQuietly(pw);
    

postman测试

以上是关于Java Httpclient 文件上传与接收的主要内容,如果未能解决你的问题,请参考以下文章

springMVC + hadoop + httpclient 文件上传请求直接写入hdfs

httpclient 实现文件上传中转

java模拟http请求上传文件,基于Apache的httpclient

httpclient 上传图片

Java使用HttpClient以multipart/form-data向接口上传文件

Java 中使用 HttpClient 4.3.6 进行文件上传