實戰演練java 調用http介面 post 例子

來源:互聯網
上載者:User
發起請求:

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 {@AutowiredIntfConfigService intfConfigService;@AutowiredIntfConfigLogService intfConfigLogService;@RequestMapping("send")@ResponseBodypublic 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;}}
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.