我是靠谱客的博主 笨笨鸡,最近开发中收集的这篇文章主要介绍HttpPost接口请求的数据传输方式,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

第一种:以json字符串的格式传递

xmlInfo是要传递的json字符串(如何把数据转化为json格式可参考我的json转化文章),apiKeyId是我的实际业务需要传递的一个值,不需要可取消,,url是请求路径

  public static String doHttpPostWithSSL(String xmlInfo, String URL,String apiKeyId) {
        log.info("发起的数据:" + xmlInfo);

        String result =null;
        try (CloseableHttpClient client =  new SSLClient()){
            HttpResponse response = null;
            HttpEntity responseEntity = null;
            HttpPost request = new HttpPost();
            request.setHeader("KeyId", apiKeyId);
            request.setHeader(APP_CODE, FMS_CODE);
            request.setHeader("Content-Type", "application/json; charset=utf-8");
            request.setURI(new URI(URL));
            request.setEntity(new StringEntity(xmlInfo, "UTF-8"));
            response = client.execute(request);
            responseEntity = response.getEntity();
            result = EntityUtils.toString(responseEntity);
        } catch (Exception e) {
            e.printStackTrace();
        }
        log.info("返回的数据:" + result);
        return result;
    }

这种格式对应的postman演示:
在这里插入图片描述

第二种:以form-data的格式传递

这种格式可传递多种类型的数据,包括file文件,就是类似表单提交

   public static String ocrDistinguish(String jsonString,String url,File file) throws ClientProtocolException, IOException {
        Map<String,String> map = JsonMapper.MAPPER.toMap(jsonString);
        MultipartEntityBuilder builder = MultipartEntityBuilder.create()
                .setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
                .setCharset(Charset.forName("UTF-8"))
                .addPart("file", new FileBody(file))
                .addTextBody("ifNeedOcr", map.get("ifNeedOcr"))
                .addTextBody("pathCode",map.get("pathCode"))
                .addTextBody("reqUuid", map.get("reqUuid"))
                .addTextBody("orgCode", map.get("orgCode"))
                .addTextBody("appId", map.get("appId"))
                .addTextBody("appKey", map.get("appKey"))
                .addTextBody("appSecret", map.get("appSecret"));
        if (StringUtils.isNotBlank(map.get("fileId"))) builder.addTextBody("fileId", map.get("fileId"));
        if (StringUtils.isNotBlank(map.get("docType"))) builder.addTextBody("docType", map.get("docType"));
        return Request.Post(url)
                .socketTimeout(100000)
                .connectTimeout(100000)
                .body(builder.build()).execute().returnContent().asString();
    }
}

这种格式对应的postman演示:
在这里插入图片描述

最后

以上就是笨笨鸡为你收集整理的HttpPost接口请求的数据传输方式的全部内容,希望文章能够帮你解决HttpPost接口请求的数据传输方式所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(63)

评论列表共有 0 条评论

立即
投稿
返回
顶部