【Java使用HttpPost请求第三方接口】

Java使用HttpPost请求第三方接口

1、接口文档说明:

1、基于HTTP+POST方式发起请求
2、请求数据和响应数据格式均使用JSON数据格式;
3、消息头说明
	{
    	"head1":"head1-value",
  	"head2":"head2-value",
  	"head3":"head3-value",
		"head4":"head4-value"
	}
4、请求参数
	{
	  	"param1":"param1-value",
	 	"param2":"param2-value",
		"param3":"param3-value",
	 	"param4":"param4-value",
		"body":{	
			"body1":"body1-value",       
			"body2":[
			    {           
			       "field":"fieldvalue",
			       "body2_2": 
			             [      
			               {
			         		  "field":"fieldvalue"
			               },
			               .....                        
			             ],
			       "body2_3":
			            [
			              {
			                "field":"fieldvalue"
			              },
			              .....
			            ],
			       
			       "body2_4": 
			           [
			              {
			                "field":"fieldvalue"
			              },
			              .....
			           ],          
			       
			       "body2_5":
			          [
			            {
			               "field":"fieldvalue"
			            },
			            ...... 
			          ],
			          	     
			      "body2_6": 
			         [
			           {
			             "field":"fieldvalue"
			           },
			           ...... 
			         ],
			      "body2_7": 
			         [
			           {
			             "field":"fieldvalue"
			           },
			           ......
			         ]          	
			    },
			    .....          
			 ]
		}
	}

2、引入依赖

<!--        Http-->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpcore</artifactId>
            <version>4.4.12</version>
        </dependency>
        <dependency>
            <groupId>com.arronlong</groupId>
            <artifactId>httpclientutil</artifactId>
            <version>1.0.4</version>
        </dependency>

        <!--json解析-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.47</version>
        </dependency>

3、创建工具类

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.HashMap;

/**
 * @Author llj
 * @Description 请求工具类
 * @date 2022-05-19 16::43
 * @Version 1.0
 **/
public class RequestHttp {

    public static final String PARAM1VALUE= "1";
    public static final String PARAM2VALUE= "2";
    public static final String PARAM3VALUE= "3";
    public static final String PARAM4VALUE= "4";
    
    public static final String HEAD1VALUE= "1";
    public static final String HEAD2VALUE= "2";
    public static final String HEAD3VALUE= "3";
    public static final String HEAD4VALUE= "4";

    public static String request(String url,HashMap<String,Object> paramMap){
        paramMap.put("param1",PARAM1VALUE);
        paramMap.put("param2",PARAM2VALUE);
        paramMap.put("param3",PARAM3VALUE);
        paramMap.put("param4",PARAM4VALUE);
        //map转json
        String json = JSONObject.toJSONString(paramMap);
        String returnValue = "这是默认返回值,接口调用失败";
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        HttpEntity entity = null;
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        try{
            //第一步:创建HttpClient对象
            httpClient = HttpClients.createDefault();
            //第二步:创建httpPost对象
            HttpPost httpPost = new HttpPost(url);
			//第三步:设置请求头
            httpPost.addHeader("head1",HEAD1VALUE);
            httpPost.addHeader("head2",HEAD2VALUE);
            httpPost.addHeader("head3",HEAD3VALUE);
            httpPost.addHeader("head4",HEAD4VALUE);
            //第四步:给httpPost设置JSON格式的参数
            StringEntity requestEntity = new StringEntity(json,"UTF-8");
            requestEntity.setContentEncoding("UTF-8");
            httpPost.setHeader("Content-type", "application/json");
            httpPost.setEntity(requestEntity);
            //第五步:发送HttpPost请求,获取返回值
            response = httpClient.execute(httpPost); //调接口获取返回值时,必须用此方法
            returnValue = httpClient.execute(httpPost,responseHandler); //调接口获取返回值时,必须用此方法

            entity = response.getEntity();
            returnValue = EntityUtils.toString(entity, "UTF-8");
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
        finally {
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        //第六步:处理返回值
        System.out.println(returnValue);
        return returnValue;
    }
}

4、Java代码实现

	//第三方接口地址
    String req_url = "https://ip:端口号/test/test1";

    /**
     * @return
     */
    @GetMapping("test1")
    public String queryHilist1(@RequestParam("param")String param) {
        HashMap<String, Object> hashMap = new HashMap<>();
        //参数body
        HashMap<String, Object> body = uploadReportService.getBodyInfo(param);
        if (body==null){
            return "无效参数!!!";
        }
        //body下的body2
        List<HashMap<String, Object>> body2= uploadReportService.getRptsInfo(param);

        //  rpts下的organs  该患者有哪些科室的项目
        List<HashMap<String,Object>> body2_2= uploadReportService.getOrgansInfo(param);
        body2.get(0).put("body2_2",body2_2);

        //  rpts下的items  该患者有哪些体检项目
        List<HashMap<String,Object>> body2_3= uploadReportService.getTtemsInfo(param);
        body2.get(0).put("body2_3",body2_3);

        //  rpts下的summarys
        List<HashMap<String,Object>> body2_4= uploadReportService.getSummarysInfo(param);
        body2.get(0).put("body2_4",body2_4);

        //   rpts下的advices
        List<HashMap<String,Object>> body2_5= uploadReportService.getAdvicesInfo(param);
        body2.get(0).put("body2_5",body2_5);

        //    rpts下的raw_datas 图片信息
        List<HashMap<String,Object>> body2_6= uploadReportService.getRaw_datasInfo(param);
        body2.get(0).put("body2_6",body2_6);

        body.put("body2",body2);
        hashMap.put("body",body);
        return RequestHttp.request(req_url, hashMap);
    }

5、调用接口,查看返回值信息

{"errMsg":"成功!","result":0}

版权声明:本文为qq_44690366原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
THE END
< <上一篇
下一篇>>