JAVA接口连接-使用jdk自带
1.获得页面的请求参数
// 获得请求中的数据
HttpServletRequest request = WebUtil.getRequest();
// 将得到的请求数据转换城对应的实体
OrderEntity order = JsonUtil.toBean(request, OrderEntity.class);
String caddress = order.getCaddress();
caddress = caddress.replaceAll("undefined", "");
order.setCaddress(caddress);
// 从session中取得登录的信息
HttpSession session = request.getSession();
UserRest userRest = (UserRest) session.getAttribute("userRest");
if (userRest != null) {
// 如果有登录信息,就取出其中的登录
order.setUserName(userRest.getUserName());
// 调用service中的创建订单的方
String jsonString = orderService.createOrder(order);
// 包装成json格式再传回去
jsonBean.setDetail(jsonString);
return jsonBean;
} else {
//未登录状态下�?
String jsonString = orderService.createOrder(order);
// 包装成json格式再传回去
jsonBean.setDetail(jsonString);
return jsonBean;
}
2.建立连接,发送请求
String urls = createOrderUrl;
// 创建Url对象
URL url = new URL(urls);
// 获得连接
HttpURLConnection httpConn = ((HttpURLConnection) url.openConnection());
// 设置请求头的参数
httpConn.addRequestProperty("Conten-Type",
"application/json;charset=utf-8");
// 设置请求方式为POST
httpConn.setRequestMethod("POST");
httpConn.setDoOutput(true);
httpConn.setAllowUserInteraction(false);
// 获得输出
PrintStream ps = new PrintStream(httpConn.getOutputStream());
// 创建json格式的对象,并将参数依次放入
JSONObject jsonObject = new JSONObject();
//添加用户
jsonObject.put("userName", order.getUserName());
//添加属
jsonObject.put("shipperName", order.getShipperName());
//添加属
jsonObject.put("shipperPhone", order.getShipperPhone());
//添加属
jsonObject.put("saddress",
EsbStringUtil.changeStr(order.getSaddress()));
//添加属
jsonObject.put("conName", order.getConName());
//添加属
jsonObject.put("conPhone", order.getConPhone());
//添加属
jsonObject.put("caddress",
EsbStringUtil.changeStr(order.getCaddress()));
jsonObject.put("couponCode", order.getCouponCode());
//添加属
jsonObject.put("remark", order.getRemark());
//添加属
jsonObject.put("openId", order.getOpenId());
// 写入输出
ps.print("order=" + jsonObject);
// 关闭输出
ps.close();
InputStream input = httpConn.getInputStream();
String jsonString = IOUtils.toString(input);
if (null != jsonString) {
return jsonString;
}