使用工具: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/httpclientcompile group: 'org.apache.httpcomponents', name: 'httpclient', version: '4.5.3'// https://mvnrepository.com/artifact/org.apache.httpcomponents/httpmimecompile group: 'org.apache.httpcomponents', name: 'httpmime', version: '4.5.3'// https://mvnrepository.com/artifact/org.apache.httpcomponents/httpcorecompile 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);content.put("name", "数据" + i);contentList.add(content);}main.put("content", contentList);JSONObject jsonObject = JSONObject.fromObject(main);System.out.println("jsonObject:" + jsonObject);
//        //json字符串,去网上格式化一下,直接贴过来,然后解析成json
//        String jsonString = "{\n" +
//                "    \"token\": \"stream data\", \n" +
//                "    \"content\": [\n" +
//                "        {\n" +
//                "            \"id\": \"1\", \n" +
//                "            \"name\": \"3ba39425fec1965f4d088d2f.bmp\"\n" +
//                "        }, \n" +
//                "        {\n" +
//                "            \"id\": \"2\", \n" +
//                "            \"name\": \"09b3970fd3f5cc65b1351da4.bmp\"\n" +
//                "        }, \n" +
//                "        {\n" +
//                "            \"id\": \"3\", \n" +
//                "            \"name\": \"89ff57d93cd1b72cd0164ec9.bmp\"\n" +
//                "        }\n" +
//                "    ]\n" +
//                "}";
//        JSONObject jsonObject = JSONObject.parseObject(jsonString);return jsonObject;}//模拟json数组数据private static JSONArray getJsonArray() {List<Map<String, Object>> contentList = new ArrayList<>();for (int i = 0; i < 4; i++) {Map<String, Object> content = new HashMap<>();content.put("id", i);content.put("name", "array数据" + i);contentList.add(content);}JSONArray jsonArray =JSONArray.fromObject(contentList);System.out.println("jsonArray:" + jsonArray);return jsonArray;}

主函数:

   /*** 主函数* @param args* @throws Exception*/public static void main(String args[]) throws Exception {//模拟流文件及参数上传
//        testStreamUpload();//httpClient模拟文件上传testFileParamUpload();//httpClient模拟发送json对象,用JSONObject接收testJSONObjectUpload();}
/*** httpClient模拟文件上传*/static void testFileParamUpload() {String url = "http://127.0.0.1:8090/kty/test/receiveHttpClientWithFile";//json字符串,模拟了一个,传图片名字吧Map<String, Object> param = new HashMap<>();param.put("paramString", "i'm paramString!");param.put("paramJSONObject", getJsonObj().toString());param.put("paramJSONArray", getJsonArray().toString());doPostFileAndParam(url, getFileList(), param);}/*** 测试发送json对象并用json对象接收*/static void testJSONObjectUpload(){String url = "http://127.0.0.1:8090/kty/test/receiveHttpClientJSONObject";doPostJSONObject(url, getJsonObj(), getJsonArray());}
  • 文件和参数的 发送 和 接收  ,接收的时候要对应key value

    testFileParamUpload

发送 httpClient 请求:

/*** httpclient* 发送文件和部分参数** @return*/public static String doPostFileAndParam(String url, List<Map<String, Object>> fileList, Map<String, Object> param) {String result = "";//新建一个httpclientCloseableHttpClient httpclient = HttpClients.createDefault();try {//新建一个Post请求HttpPost httppost = new HttpPost(url);//新建文件对象MultipartEntityBuilder reqEntity = MultipartEntityBuilder.create();ContentType contentType = ContentType.create("text/plain", "UTF-8");//添加参数的时候,可以都使用addPart,然后new一个对象StringBody、FileBody、BinaryBody等reqEntity//设置编码,这两个一定要加,不然文件的文件名是中文就会乱码.setCharset(Charset.forName("utf-8"))//默认是STRICT模式,用这个就不能使用自定义的编码了.setMode(HttpMultipartMode.BROWSER_COMPATIBLE)//也可以使用reqEntity.setLaxMode();具体的可以查看MultipartEntityBuilder类//这个方法其实就是addPart(name, new StringBody(text, contentType));.addTextBody("paramString", param.get("paramString").toString())//textbody传送的都是String类型,所以接收只能用string接收,接收后转成json对象就可以了(后面一种方法直接可以用JSONObject接收,不论参数名).addTextBody("paramJSONObject", param.get("paramJSONObject").toString(), ContentType.APPLICATION_JSON).addTextBody("paramJSONArray", param.get("paramJSONArray").toString(), ContentType.APPLICATION_JSON)//如果contentType不够用,可以自己定义.addPart("paramPart", new StringBody("addPart你好", contentType));//拼接文件类型for (Map<String, Object> elem : fileList) {//拼接参数String location = elem.get("location").toString();String fileName = elem.get("fileName").toString();System.out.println(fileName);File file = new File(location);//添加二进制内容,这个方法可以放流进去,也可以放文件对象进去,很方便InputStream fileStream = new FileInputStream(file);reqEntity.addBinaryBody("file", fileStream, ContentType.APPLICATION_OCTET_STREAM, fileName);//文件的Contenttype貌似只要合理就行,流、form_data、或者干脆不填
//                reqEntity.addBinaryBody("file", file, ContentType.APPLICATION_OCTET_STREAM, fileName);//也可以用addPart添加
//                reqEntity.addPart("file", new FileBody(file));}//将数据设置到post请求里httppost.setEntity(reqEntity.build());//执行提交System.err.println("执行请求:" + httppost.getRequestLine());CloseableHttpResponse response = httpclient.execute(httppost);//获得返回参数InputStream is = response.getEntity().getContent();BufferedReader in = new BufferedReader(new InputStreamReader(is));StringBuffer buffer = new StringBuffer();String line = "";while ((line = in.readLine()) != null) {buffer.append(line);}result = buffer.toString();System.out.println("收到的返回:" + result);//关闭返回response.close();} catch (Exception e) {e.printStackTrace();} finally {try {//关闭httpclienthttpclient.close();} catch (Exception e) {e.printStackTrace();}}return result;}

接收:

/*** httpclient 接收文件* 文件需要从request里解析,可以自己手动解析,也可以像我这样直接用multirequest接收,然后用getFiles就能拿到文件* 其他参数String类型** @return* @RequestBody 加了这个才能区分,不然默认都是String的key value格式,会报mismatch arguments*/@PostMapping("/receiveHttpClientWithFile")public String receiveHttpClientWithFile(MultipartHttpServletRequest multiRequest, String paramString, String paramPart,String paramJSONObject, String paramJSONArray) {String result = "成功收到请求";System.out.println("收到请求,开始执行");System.out.println("paramString===" + paramString);System.out.println("paramPart===" + paramPart);//这里就可以解析string为json对象System.out.println("paramJSONObject===" + paramJSONObject);JSONObject resJsonObj = JSONObject.fromObject(paramJSONObject);System.out.println("json对象里的第一个元素token===" + resJsonObj.get("token"));//这里就可以解析string为jsonarray数组System.out.println("paramJSONArray===" + paramJSONArray);JSONArray resJsonArray = JSONArray.fromObject(paramJSONArray);System.out.println(resJsonArray.get(1));List<MultipartFile> fileList = multiRequest.getFiles("file");for (MultipartFile elem : fileList) {System.out.println(elem.getOriginalFilename());System.out.println("file===" + elem.getOriginalFilename() + "--" + elem.getSize() + elem.getContentType());}return result;}

请求输出:

接收输出:

  • json对象的 发送 和 接收 ,接收方用 @RequestBody,无视对应key

    testJSONObjectUpload()

发送 httpClient :

/*** httpclient* 发送json对象* StringEntity可以直接用JSONObject接收** @return*/public static String doPostJSONObject(String url, JSONObject jsonObject, JSONArray jsonArray) {String result = "";//新建一个httpclientCloseableHttpClient httpclient = HttpClients.createDefault();try {//新建一个Post请求HttpPost httppost = new HttpPost(url);//新建json对象StringEntity stringEntity = new StringEntity(jsonObject.toString(), ContentType.APPLICATION_JSON);
//            StringEntity stringEntity = new StringEntity(jsonArray.toJSONString(), ContentType.APPLICATION_JSON);//将数据设置到post请求里httppost.setEntity(stringEntity);//执行提交System.err.println("执行请求:" + httppost.getRequestLine());CloseableHttpResponse response = httpclient.execute(httppost);//获得返回参数InputStream is = response.getEntity().getContent();BufferedReader in = new BufferedReader(new InputStreamReader(is));StringBuffer buffer = new StringBuffer();String line = "";while ((line = in.readLine()) != null) {buffer.append(line);}result = buffer.toString();System.out.println("收到的返回:" + result);//关闭返回response.close();} catch (Exception e) {e.printStackTrace();} finally {try {//关闭httpclienthttpclient.close();} catch (Exception e) {e.printStackTrace();}}return result;}

接收:

    /*** httpclient 接收json对象** @return*/@PostMapping("/receiveHttpClientJSONObject")public String receiveHttpClientJSONObject(@RequestBody JSONObject param) {String result = "成功收到请求";System.out.println("收到请求,开始执行");System.out.println("param===" + param);System.out.println("json对象里的第一个元素token===" + param.get("token"));return result;}

发送方控制台打印:

接收方控制台打印:

综上,代码贴着以后自己可以直接用了,发到网上,欢迎各路大神给出宝贵建议

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

  1. discard connection丢失数据_python kafka 生产者发送数据的三种方式

    python kafka 生产者发送数据的三种方式 发送方式 同步发送 发送数据耗时最长 有发送数据的状态,不会丢失数据,数据可靠性高 以同步的方式发送消息时,一条一条的发送,对每条消息返回的结果判断 ...

  2. curl 发送 POST 请求的四种方式

    使用 curl 发送 POST 请求的四种方式: application/x-www-form-urlencoded 使用实例 $ curl localhost:3000/api/basic -X P ...

  3. 安卓 发送短信两种方式

    android中可以通过两种方式发送短信 第一:调用系统短信接口直接发送短信:主要代码如下: Java代码   //直接调用短信接口发短信 SmsManager smsManager = SmsMan ...

  4. Python 发送 email 的三种方式

    Python发送email的三种方式,分别为使用登录邮件服务器.使用smtp服务.调用sendmail命令来发送三种方法 本文原文自米扑博客:Python 发送 email 的三种方式 Python发 ...

  5. Kafka生产者发送消息的三种方式

    Kafka是一种分布式的基于发布/订阅的消息系统,它的高吞吐量.灵活的offset是其它消息系统所没有的. Kafka发送消息主要有三种方式: 1.发送并忘记 2.同步发送 3.异步发送+回调函数 下 ...

  6. 接收Http请求的几种方式

    最近在开发过程中,遇到了我们公司的几个老项目,采用的是传统单体项目,这种项目之间需要交互,项目A请求项目B,B将结果回调给A,我们采用了Http Post请求的方式,在接收Http请求的时候,遇到了不 ...

  7. ajax发送请求和数据返回,Ajax发送和接收请求

    首先Ajax的不刷新页面提交数据 基本上浏览器能接收的信息,Ajax都可以接收,ex:字符串,html标签,css标签,xml格式内容,json格式内容等等..... // IE浏览器 if(Acti ...

  8. python requests session post_requests.session()发送请求 和使用requests直接发送请求的区别...

    requests.session()发送请求 和使用requests直接发送请求的区别 一.Session 在requests里,session对象是一个非常常用的对象,这个对象代表一次用户会话:从客 ...

  9. 返回ajax有几种方式,java ajax返回 Json 的 几种方式

    方式 1. : 自写代码转 Json 需要  HttpHttpServletRequest request  HttpServletResponse response 后台 : @RequestMap ...

最新文章

  1. 实现SSTab单个选项卡代码
  2. AI芯片:从历史看未来
  3. 网络推广专员浅析如何在日常网络推广过程中增加网站转化率?
  4. 支持本地 持久化的 单机版 consul 服务
  5. Problem executing scripts APT::Update::Post-Invoke-Success ‘if /usr/bin/test -w /var/lib/command-not
  6. 转载:opencv:关于vs opencv每次都要配置的解决方案
  7. Unity3D 重写下拉菜单/Dropdown组件、开启每个按钮可用
  8. JAVA的array中indexOf
  9. [C/C++标准库]_[0基础]_[优先队列priority_queue的使用]
  10. HDU 1573 X问题 [中国剩余定理]
  11. python中append,pop,extend,remove的区别
  12. hdu1247 Hat’s Words 字符串模拟
  13. 2×3卡方检验prism_何时应该使用非参数检验?
  14. 研发面试问题回答技巧
  15. MathType安装和解决不能Crtl+V的问题
  16. 用计算机弹暖暖数字代码,奇迹暖暖网页版计算器
  17. 项目成功和失败的几大因素
  18. [linux]platform总线机制与wtd驱动开发
  19. mathtype服务器 消息通知区域,MathType打开窗口太多怎么办
  20. 凌度记录仪mov视频恢复修复方法

热门文章

  1. 【WCN6856】WiFi 5G 接口启动失败问题解决
  2. 子网掩码起什么作用?
  3. 示波器基础知识100问
  4. 技术面常见问题(持续更新)
  5. 美图公司FinOps探索的那些事儿~
  6. 哪个安卓模拟器比较好用 2023年好用的安卓模拟器推荐
  7. 如花搞笑图片集锦(转贴)
  8. 最新论文笔记(+11):Privacy-Preserving Searchable Encryption Framework for Permissioned Blockchain Networks
  9. 如果可以随意 Emoji 组合,你能让两个表情包碰撞出什么花样?
  10. Angular4的双向数据绑定