Maison > Java > javaDidacticiel > le corps du texte

Exercice pratique Java appelant un exemple de publication d'interface http

php是最好的语言
Libérer: 2018-08-09 15:23:04
original
2548 Les gens l'ont consulté

Initier la demande :

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();
		}
	}
}
Copier après la connexion

Récepteur :

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;
	}
}
Copier après la connexion

Recommandations associées :

Je souhaite effectuer un appel PHP au service Web Java Exemples d'interfaces, mais.

Exemples de java appelant directement des scripts python

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Étiquettes associées:
source:php.cn
Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Tutoriels populaires
Plus>
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal