多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
1. 引入httpclient依赖 ``` <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.5</version> </dependency> ``` 2. 工具类 ``` package net.aexit.galaxy.octopus.zongjian.util; import com.alibaba.fastjson.JSONObject; import net.aexit.galaxy.octopus.zongjian.ministry.model.A14PrintImage; import org.apache.http.*; 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.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import org.apache.log4j.Logger; import java.io.IOException; /** * Created by dailin on 2018/9/18. */ public class HttpUtil { private static Logger logger = Logger.getLogger(HttpUtil.class); /** * 发送post请求 * * @param url 请求地址 * @param object 请求参数对象 * @throws IOException */ public static String doPost(String url, Object object) throws IOException { CloseableHttpClient httpclient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost(url);// 创建httpPost httpPost.setHeader("Accept", "application/json"); httpPost.setHeader("Content-Type", "application/json"); StringEntity entity = new StringEntity(JSONObject.toJSONString(object), "utf-8"); System.out.println(JSONObject.toJSONString(object)); httpPost.setEntity(entity); CloseableHttpResponse response = null; try { response = httpclient.execute(httpPost); StatusLine status = response.getStatusLine(); int state = status.getStatusCode(); if (state == HttpStatus.SC_OK) { HttpEntity responseEntity = response.getEntity(); return EntityUtils.toString(responseEntity); } else { logger.error("请求返回:" + state + "(" + url + ")"); } } finally { if (response != null) { try { response.close(); } catch (IOException e) { e.printStackTrace(); } } try { httpclient.close(); } catch (IOException e) { e.printStackTrace(); } } return null; } public static void main(String[] args) throws Exception { A14PrintImage a14PrintImage = new A14PrintImage(); a14PrintImage.setDsId("111"); a14PrintImage.setVehicleNo("北京潭门"); HttpUtil.doPost("http://localhost:8888/test", a14PrintImage); } } ``` 3. conroller ``` @PostMapping(value = "/test") @ResponseBody public String test3(@RequestBody A14PrintImage img){ return "yes"; } ```