java实现文件发送、接收接口,亲测可行

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档

目录

前言

1.pom文件引入相关jar包

2.文件发送源码(废话不多说)

3.文件接收源码

总结



前言

通过HttpClient实现请求发送、接收文件。

1.pom文件引入相关jar包

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

2.文件发送源码(废话不多说)

代码如下:

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

/**
 * 调用跨网文件发送接口
 * @author tingh
 *
 */
public class HttpSendFile {

    private static final Charset CHARSET_UTF8 = Charset.forName("UTF-8");

    /**
     * 调用文件发送接口
     * @param file
     * @param info
     * @param remote_url
     * @return
     */

    public static Map<String, Object> call_sendFile(File file, String remote_url){
        CloseableHttpClient httpclient = HttpClients.createDefault();
        Map<String, Object> responseMap = new HashMap<>();
        try{
            HttpPost httpPost = new HttpPost(remote_url);

            //创建接口需要的参数
            MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
            ContentType infoCType = ContentType.create("application/json", CHARSET_UTF8);
            ContentType fileCType = ContentType.create("application/octet-stream", CHARSET_UTF8);
            entityBuilder.addPart("file", new FileBody(file, fileCType));
         
            HttpEntity entity = entityBuilder.build();
            httpPost.setEntity(entity);

            //调用跨网文件发送接口
            HttpResponse response = httpclient.execute(httpPost);
            //获取响应信息
            HttpEntity responseEntity = response.getEntity();
            if(responseEntity != null){
                result = EntityUtils.toString(responseEntity, CHARSET_UTF8);
            }
            responseMap.put("code", response.getStatusLine().getStatusCode());
            responseMap.put("result", result);
        } catch (IOException e){
            e.printStackTrace();
        } catch (Exception e){
            e.printStackTrace();
        } finally {
            try {
                httpclient.close();
            } catch (Exception e){
                e.printStackTrace();
            }
        }
        return responseMap;
    }
}
 

 注意注意注意!!!!

httppost请求无需加请求头addHeader、setHeader,我用postman测试会报错。

返回结果可以自己封装,我用map处理了

注意关闭请求

3.文件接收源码


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.ws.rs.core.MediaType;
import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;

/**
 * 文件接收接口
 *
 * @return
 */
@RestController
public class HttpReceiveFile {

    public HttpReceiveFile() {

    }

    @RequestMapping(value = "/receivFile", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON, consumes = MediaType.MULTIPART_FORM_DATA)
    public void receivFile(MultipartFile file) {

      
        System.out.println("接收文件名:" + fileName);
        try {
            if (fileName != null && !fileName.equals("")) {
                //写入接收文件
                File newFile = new File(infoObj.getString("uid"));//改成你们的参数逻辑
                file.transferTo(Paths.get(newFile.getPath()));
                System.out.println("接收文件写入成功");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

 没啥注意点,就是请求类型post,生成的文件用了uuid随机生成。


总结

一个简单的文件发送、接收接口。无聊记录一下,方便自己直接拿来用。如果有自己相关逻辑处理,发送文件接口添加参数,将参数写入到entityBuilder.addPart里。接收文件时,将逻辑信息json解析出来,获取想要的相关数据。


                
  • 4
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值