http 인터페이스를 호출하는 실습 java 포스트 예제
요청 시작:
import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.net.HttpURLConnection; import java.net.URL; import java.text.SimpleDateFormat; import org.apache.http.util.TextUtils; import com.alibaba.fastjson.JSONObject; import cn.com.doone.tx.cloud.tool.common.util.Md5Util; import java.util.Collection; import java.util.Date; public class IntfMain { //post请求方法 public static String post(String strURL, String params) { System.out.println(strURL); System.out.println(params); String result = ""; BufferedReader reader = null; StringBuilder sb = new StringBuilder(); BufferedReader in = null; try { URL url = new URL(strURL);// 创建连接 HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setDoInput(true); connection.setUseCaches(false); connection.setInstanceFollowRedirects(true); connection.setRequestMethod("POST"); // 设置请求方式 connection.setRequestProperty("Accept", "application/json"); // 设置接收数据的格式 connection.setRequestProperty("Content-Type", "application/json"); // 设置发送数据的格式 connection.connect(); if (params != null && !TextUtils.isEmpty(params)) { byte[] writebytes = params.getBytes(); // 设置文件长度 // connection.setRequestProperty("Content-Length", String.valueOf(writebytes.length)); OutputStream outwritestream = connection.getOutputStream(); outwritestream.write(params.getBytes()); outwritestream.flush(); outwritestream.close(); } int responseCode = connection.getResponseCode(); InputStream inputStream = null; if (responseCode == 200) { inputStream = new BufferedInputStream(connection.getInputStream()); } else { inputStream = new BufferedInputStream(connection.getErrorStream()); } in = new BufferedReader(new InputStreamReader(inputStream, "UTF-8")); String line; while ((line = in.readLine()) != null) { result+=line; } } catch (Exception e) { e.printStackTrace(); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } } return result; } public static void main(String[] args) { //String url = "http://localhost:28001/intf/send"; String url = "http://###:##/gdctsWeb/intf/send"; long createTime = new Date().getTime(); long reqTime = new Date().getTime(); String bodyStr="{\"creator\":\"4\",\"operator\":\"4\",\"operateType\":\"ADD\",\"channelCode\":\"V7\",\"synId\":\"556445\",\"name\":\"計算機团体345\",\"password\":\"345123\",\"registerTime\":\"2018-07-0121:00:00\",\"account\":\"account041\",\"custType\":\"2\",\"bindNumber\":\"15055556666\",\"groupContact\":[{\"contactName\":\"团体联系人\",\"contactNumber\":\"155555555\",\"email\":\"2222@qq.com\",\"occupation\":\"leader\",\"qq\":\"313131\",\"remark\":\"联系人备注\"}],\"groupInfoEvt\":[{\"address\":\"团体地址\",\"areaCode\":\"111\",\"busiArea\":\"222\",\"cityCode\":\"322\",\"custIndustry\":\"行业\",\"groupNature\":\"性质\",\"groupSize\":\"大\",\"name\":\"某团体客户\",\"provinceCode\":\"1111\",\"registeredCapital\":\"资本\",\"remark\":\"备注\",\"zipCode\":\"350000\"}],\"members\":[{\"name\":\"名称\",\"contactNumber\":\"111444\",\"cerType\":\"1\",\"cerNo\":\"6874268552552\",\"sex\":\"1\",\"age\":\"10\"}],\"resource\":\"介绍\"}"; JSONObject paramJson = new JSONObject(true); JSONObject body = new JSONObject(true); body=JSONObject.parseObject(bodyStr); JSONObject head = new JSONObject(true); String intfCode = "CRM_CUSTGROUP004"; String sysSecret="GRD01"; String sysCode="V7"; String signOri=sysCode+intfCode+sysSecret+reqTime; Collection<Object> values = body.values(); for (Object v : values) { signOri=signOri+v.toString(); } //System.out.println(signOri); String sign = Md5Util.MD5(signOri); String headStr="{\"sysCode\":\""+sysCode+"\",\"intfCode\":\""+intfCode+"\",\"reqTime\":\""+reqTime+"\",\"sign\":\""+sign+"\"}"; head=JSONObject.parseObject(headStr); paramJson.put("head", head); paramJson.put("body", body); try { String json = paramJson.toJSONString(); String postWithJSON = post(url, json); System.out.println(postWithJSON); } catch (Exception e) { e.printStackTrace(); } } }
수신자:
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.URLDecoder; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Enumeration; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.jsp.tagext.TryCatchFinally; import org.apache.http.protocol.HTTP; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.alibaba.fastjson.JSONObject; import cn.com.doone.tx.cloud.system.service.IntfConfigService; import cn.com.doone.tx.cloud.system.utils.JsonUtils; import cn.com.doone.tx.cloud.system.utils.ServerHeaderSyn; import cn.com.doone.tx.cloud.system.utils.ServerRespSyn; import cn.com.doone.tx.cloud.system.evt.RequestJsonEvt; import cn.com.doone.tx.cloud.system.service.IntfConfigLogService; import cn.com.doone.tx.cloud.tool.common.invoke.ServerResp; import cn.com.doone.tx.cloud.tool.common.util.Md5Util; import cn.com.doone.tx.cloud.tool.web.base.BaseController; //v7系统同步接口 @Controller @EnableAutoConfiguration @RequestMapping("/intf") public class IntfConfigController extends BaseController { @Autowired IntfConfigService intfConfigService; @Autowired IntfConfigLogService intfConfigLogService; @RequestMapping("send") @ResponseBody public ServerRespSyn<Object> send(HttpServletRequest request) throws IOException { ServerRespSyn<Object> respV7 = new ServerRespSyn<>(); ServerHeaderSyn respV7Header = new ServerHeaderSyn(); ServerResp<Object> respLogAdd = new ServerResp<>(); ServerResp<Object> resp = new ServerResp<>(); HashMap<String, Object> pram = new HashMap<String, Object>(); // 读取请求内容 BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream())); String line = null; StringBuilder sb = new StringBuilder(); while ((line = br.readLine()) != null) { sb.append(line); } // 将资料解码 String reqBody = sb.toString(); String str = URLDecoder.decode(reqBody, HTTP.UTF_8); RequestJsonEvt jsonEvt = JsonUtils.fromJson(str, RequestJsonEvt.class); Map<String, Object> head = jsonEvt.getHead(); Map<String, Object> body = jsonEvt.getBody(); String sysSecret="GRD01"; String signMy =head.get("sysCode").toString()+head.get("intfCode").toString()+ sysSecret +head.get("reqTime").toString(); String sign = head.get("sign").toString(); for (Object m: body.values()) { signMy=signMy+ JsonUtils.toJson(m); } try { ServerResp<Object> respConfigList = intfConfigService.getIntfConfigList(pram); List<LinkedHashMap<String, Object>> list = (List<LinkedHashMap<String, Object>>) respConfigList.getBody(); if (Md5Util.MD5(signMy).equals(sign)) { for (LinkedHashMap<String, Object> linkedHashMap : list) { if (head.get("intfCode").equals(linkedHashMap.get("intfCode"))){ HashMap<String, Object> pramLog = new HashMap<String, Object>(); HashMap<String, Object> pramLog1 = new HashMap<String, Object>(); LinkedHashMap<String, Object> mapLog = new LinkedHashMap<>(); try { pramLog.put("callSystemCode", "V7"); pramLog.put("intfSystemCode", "CRM"); pramLog.put("intfUrl",linkedHashMap.get("intfUrl")); pramLog.put("intfName",linkedHashMap.get("intfName")); pramLog.put("intfCode", linkedHashMap.get("intfCode")); pramLog.put("intfParamsIn",str ); pramLog.put("creator", 4); pramLog.put("operator",4); respLogAdd = intfConfigLogService.addLog(pramLog); mapLog = (LinkedHashMap<String, Object>) respLogAdd.getBody(); resp = intfConfigService.doSend(body, linkedHashMap.get("intfUrl").toString()); if(resp.isSuccess()) { pramLog1.put("id", mapLog.get("id")); pramLog1.put("resDesc", "调用成功"); pramLog1.put("status", resp.getHead().getRespCode()); pramLog1.put("intfParamsOut",JsonUtils.toJson(resp)); SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmssSSS"); String resTime = formatter.format(new Date()); respV7Header.setResTime(resTime); respV7Header.setRespCode(0); respV7Header.setSign(sign); respV7Header.setRespMsg(resp.getHead().getRespMsg()); respV7.setHead(respV7Header); respV7.setBody(resp.getBody()); }else { pramLog1.put("id", mapLog.get("id")); pramLog1.put("resDesc", resp.getHead().getRespMsg()); pramLog1.put("status", resp.getHead().getRespCode()); pramLog1.put("intfParamsOut",JsonUtils.toJson(resp)); SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmssSSS"); String resTime = formatter.format(new Date()); respV7Header.setResTime(resTime); respV7Header.setRespCode(1); respV7Header.setSign(sign); respV7Header.setRespMsg(resp.getHead().getRespMsg()); respV7.setHead(respV7Header); respV7.setBody(resp.getBody()); } } catch (Exception e) { pramLog1.put("id", mapLog.get("id")); pramLog1.put("resDesc", "调用失败"); pramLog1.put("status", "-1"); pramLog1.put("intfParamsOut",e.getMessage()); SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmssSSS"); String resTime = formatter.format(new Date()); respV7Header.setResTime(resTime); respV7Header.setRespCode(1); respV7Header.setSign(sign); respV7Header.setRespMsg(resp.getHead().getRespMsg()); respV7.setHead(respV7Header); respV7.setBody(e.getMessage()); }finally { intfConfigLogService.editLog(pramLog1); } } } }else { SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmssSSS"); String resTime = formatter.format(new Date()); respV7Header.setResTime(resTime); respV7Header.setRespCode(1); respV7Header.setSign(sign); respV7Header.setRespMsg("调用失败"); respV7.setHead(respV7Header); respV7.setBody("安全验签不一致"); } } catch (Exception e) { e.printStackTrace(); SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmssSSS"); String resTime = formatter.format(new Date()); respV7Header.setResTime(resTime); respV7Header.setRespCode(1); respV7Header.setSign(sign); respV7Header.setRespMsg("调用失败"); respV7.setHead(respV7Header); respV7.setBody(e.getMessage()); } return respV7; } }
관련 권장 사항:
Java 웹 서비스 인터페이스를 호출하는 PHP의 예를 만들고 싶지만.
위 내용은 http 인터페이스를 호출하는 실습 java 포스트 예제의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

뜨거운 주제











일부 애플리케이션이 제대로 작동하지 않는 회사의 보안 소프트웨어에 대한 문제 해결 및 솔루션. 많은 회사들이 내부 네트워크 보안을 보장하기 위해 보안 소프트웨어를 배포 할 것입니다. ...

시스템 도킹의 필드 매핑 처리 시스템 도킹을 수행 할 때 어려운 문제가 발생합니다. 시스템의 인터페이스 필드를 효과적으로 매핑하는 방법 ...

데이터베이스 작업에 MyBatis-Plus 또는 기타 ORM 프레임 워크를 사용하는 경우 엔티티 클래스의 속성 이름을 기반으로 쿼리 조건을 구성해야합니다. 매번 수동으로 ...

IntellijideAultimate 버전을 사용하여 봄을 시작하십시오 ...

많은 응용 프로그램 시나리오에서 정렬을 구현하기 위해 이름으로 이름을 변환하는 솔루션, 사용자는 그룹으로, 특히 하나로 분류해야 할 수도 있습니다.

Java 객체 및 배열의 변환 : 캐스트 유형 변환의 위험과 올바른 방법에 대한 심층적 인 논의 많은 Java 초보자가 객체를 배열로 변환 할 것입니다 ...

데이터베이스 쿼리에 tkmyBatis를 사용하는 경우 쿼리 조건을 구축하기 위해 엔티티 클래스 변수 이름을 우아하게 가져 오는 방법이 일반적인 문제입니다. 이 기사는 고정 될 것입니다 ...

Redis 캐싱 솔루션은 제품 순위 목록의 요구 사항을 어떻게 인식합니까? 개발 과정에서 우리는 종종 a ... 표시와 같은 순위의 요구 사항을 처리해야합니다.
