通过httpclient发送请求的几种方式,发送文件、参数、json对象

本文介绍了如何使用HttpClient在Java中进行HTTP POST请求,包括发送文件、参数和JSON对象的方法。特别指出文件和JSON对象不能同时发送,需要将JSON对象转换为字符串。文中提供了一个测试类,包含发送文件和参数、发送JSON对象并用@RequestBody接收的示例代码,以及对应的请求和接收输出。
摘要由CSDN通过智能技术生成

使用工具:idea

框架:gradle、springboot

实现目标:使用 httpclient 发送文件/参数/json对象

method:post

主要用到的jar包:

    compile group: 'net.sf.json-lib', name: 'json-lib', version: '2.4', classifier: 'jdk15'

    //httpclient
    // https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient
    compile group: 'org.apache.httpcomponents', name: 'httpclient', version: '4.5.3'
    // https://mvnrepository.com/artifact/org.apache.httpcomponents/httpmime
    compile group: 'org.apache.httpcomponents', name: 'httpmime', version: '4.5.3'
    // https://mvnrepository.com/artifact/org.apache.httpcomponents/httpcore
    compile group: 'org.apache.httpcomponents', name: 'httpcore', version: '4.4.6'

花了大半天终于写完这个测试类,能正常跑起来,下面主要贴出来两种 httpclient 的发送和接收,基本够用

特别注意:

  1. 文件和json对象是不能一起发送的,要发也是把json对象toString一下,见第一个方法
  2. 发送json对象,并用Requestbody接收,这种智能发对象,不能发文件,见第二个方法

预备几个方法,因为模拟数据用到的一样,所以先贴这几个公用方法:


    //模拟文件数据,这里自己改成自己的文件就可以了
    private static List<Map<String, Object>> getFileList() {
        //文件列表,搞了三个本地文件
        List<Map<String, Object>> fileList = new ArrayList<>();
        Map<String, Object> filedetail1 = new HashMap<>();
        filedetail1.put("location", "F:\\me\\photos\\动漫\\3ba39425fec1965f4d088d2f.bmp");
        filedetail1.put("fileName", "图片1");
        fileList.add(filedetail1);
        Map<String, Object> filedetail2 = new HashMap<>();
        filedetail2.put("location", "F:\\me\\photos\\动漫\\09b3970fd3f5cc65b1351da4.bmp");
        filedetail2.put("fileName", "图片2");
        fileList.add(filedetail2);
        Map<String, Object> filedetail3 = new HashMap<>();
        filedetail3.put("location", "F:\\me\\photos\\动漫\\89ff57d93cd1b72cd0164ec9.bmp");
        filedetail3.put("fileName", "图片3");
        fileList.add(filedetail3);
        return fileList;
    }

    //模拟json对象数据
    private static JSONObject getJsonObj() {
        /**
         * 这里搞json对象方法很多
         * 1.直接字符串贴过来,然后解析成json
         * 2.用map<String,Object>,做好数据之后解析成json,.toJSONString
         * 3.new 一个JSONObject对象,然后自己拼接
         * 下面的例子用map好了,这个应该通俗易懂
         */
        Map<String, Object> main = new HashMap<>();
        main.put("token", "httpclient with file stringParam jsonParam and jasonArrayParam");
        List<Map<String, Object>> contentList = new ArrayList<>();
        for (int i = 0; i < 4; i++) {
            Map<String, Object> content = new HashMap<>();
            content.put("id", i);
            cont
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值