HttpPost实现form-data形式的post请求

请求的参数:

导入maven:

<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.4.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpcore -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.4.1</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.4.1</version>
</dependency>

 

 

实例:

//json格式的参数 
Map<String,Object> receiveData= new HashMap<String, Object>();
                                receiveData.put("addTime",addtime);
                                receiveData.put("saveDate",saveday);
                                receiveData.put("id",num);
                                receiveData.put("saveTime",savetime);
                                receiveData.put("bloodsugar",bloodsugarvalue);
                                String  param= JSON.toJSONString(receiveData);
//调用工具类
doPost.simPost(param,simnumber);

/**工具类**/
 public String simPost( String  param,String simnumber)throws Exception{
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            HttpPost httppost = new HttpPost("https://iot.tronlife.com:22512/jz-iot-business/bsys/reveiveDm6001Data");
            StringBody receiveData1 = new StringBody(param,ContentType.TEXT_PLAIN);
            StringBody deviceCode = new StringBody(simnumber,ContentType.TEXT_PLAIN);
            StringBody productKey = new StringBody("Dm6001_fdfafb07-d6",ContentType.TEXT_PLAIN);
            StringBody productSecret = new StringBody("ebf0c6ba-a3dd-4c60",ContentType.TEXT_PLAIN);
//                                doPost.post(null,UrlUtil.Dm6001Data(receiveData,simnumber));
            HttpEntity reqEntity = MultipartEntityBuilder.create()
                    .addPart("receiveData",receiveData1)
                    .addPart("deviceCode",deviceCode)
                    .addPart("productKey",productKey)
                    .addPart("productSecret",productSecret)
                    .build();
            httppost.setEntity(reqEntity);
            CloseableHttpResponse response = httpclient.execute(httppost);
            try {
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    //打印获取到的返回值
                    System.out.println("Response content: " +  EntityUtils.toString(resEntity,"utf-8"));
                }
                EntityUtils.consume(resEntity);
            } finally {
                response.close();
            }
        } finally {
            httpclient.close();
        }

return null;
    }

 

posted @ 2021-02-01 10:28  彤彤qtt  阅读(4858)  评论(0编辑  收藏  举报