本人最近在处理两个系统间对象传输的问题上遇到了一些问题,比如我在A系统(java写的)传送一个对象给B系统(PHP写的),要怎么做呢?
刚开始的时候我是用httpclient的post方法,参照别人写的,写了一个测试类,然后调用,代码如下:
//这部分是测试类
private static void postRequestTest() {
String url = "http://localhost:8080/SpringMVC/process";
UserDTO userDTO = new UserDTO();
userDTO.setName("zhangshang");
userDTO.setAge(25);
JSONObject jsonParam = JSONObject.fromObject(userDTO);
JSONObject responseJSONObject = HttpRequestUtil.httpPost(url, jsonParam);
if(responseJSONObject != null && "SUCCESS".equals(responseJSONObject.get("status"))) {
JSONObject userStr = (JSONObject) responseJSONObject.get("userDTO");
userDTO = (UserDTO) JSONObject.toBean(userStr, UserDTO.class);
logger.info("http Post request process sucess");
logger.info("userDTO:" + userDTO);
}else {
logger.info("http Post request process fail");
}
}
public static JSONObject httpPost(String url,JSONObject jsonParam){
return httpPost(url, jsonParam, false);
}
public static JSONObject httpPost(String url,JSONObject jsonParam, boolean noNeedResponse){
//post请求返回结果
CloseableHttpClient httpClient = HttpClients.createDefault();
JSONObject jsonResult = null;
HttpPost method = new HttpPost(url);
try {
if (null != jsonParam) {
//解决中文乱码问题
StringEntity entity = new StringEntity(jsonParam.toString(), "utf-8");
entity.setContentEncoding("UTF-8");
entity.setContentType("application/json");
method.setEntity(entity);
}
HttpResponse result = httpClient.execute(method);
url = URLDecoder.decode(url, "UTF-8");
/**请求发送成功,并得到响应**/
if (result.getStatusLine().getStatusCode() == 200) {
String str = "";
try {
/**读取服务器返回过来的json字符串数据**/
str = EntityUtils.toString(result.getEntity());
if (noNeedResponse) {
return null;
}
/**把json字符串转换成json对象**/
jsonResult = JSONObject.fromObject(str);
} catch (Exception e) {
logger.error("post请求提交失败:" + url, e);
}
}
} catch (IOException e) {
logger.error("post请求提交失败:" + url, e);
}
return jsonResult;
}
//这部分是调用的方法
@ResponseBody
@RequestMapping(value="/process",method = RequestMethod.POST)
public String process(HttpServletRequest request, @RequestBody String requestBody) {
logger.info("process param is :{}" + requestBody);
JSONObject result = new JSONObject();
try {
JSONObject jsonObject = JSONObject.fromObject(requestBody);
UserDTO userDTO = (UserDTO) JSONObject.toBean(jsonObject, UserDTO.class);
userDTO = helloService.processService(userDTO);
//返回请求结果
result.put("status", "SUCCESS");
result.put("userDTO", userDTO);
} catch (Exception e) {
logger.info("请求处理异常! params is:{}", requestBody);
result.put("status", "FAIL");
}
return result.toString();
}
结论:只适用于同域,不能用于跨域,然后百度搜索了下,发现可以用jsonp进行跨域,废话不说,上代码:
//转json字符串数组
var jsonStr = JSON.stringify(rt.dataList);
//跨域传输products到BKK系统
$.ajax({
type : "GET",
url : "http://localhost/admin.php?m=Admin&c=Product&a=syncAdd&jsonStr="+jsonStr,
async: false,
dataType : "jsonp",
jsonp : "callback",
success : function(data) {
if (data.error) {
MESSAGE_DIALOG.error("确认发货信息同步BKK系统失败!");
} else {
MESSAGE_DIALOG.custom("提示", "确认发货信息成功同步到BKK系统!");
}
},
error : function(jqXHR) {
MESSAGE_DIALOG.error("发生错误"+jqXHR.status);
}
})
以上是js端的代码
public function syncAdd(){ $jsonp = $_GET["callback"]; $jsonStr = $_GET["jsonStr"]; $de_json = json_decode($jsonStr,TRUE); if(empty($de_json)){ echo $jsonp.'({"success":false,"msg":"失败"})'; }else{ foreach($de_json as $k=>$v){ foreach($v as $key => $val){ if(!empty($val)){ switch($key){ case "id":$info[$k]["id"] = $val;break; } } } } M("product")->addAll($info); echo $jsonp.'({"success":true,"msg":"成功"})'; } }以上是PHP的代码,这边
case "id":$info[$k]["id"] = $val;break;
[$k]后面那个id要对应数据库的字段,前面那个id是对应传过来的id,要注意了!