java呼叫介面(跨域呼叫函式)
阿新 • • 發佈:2018-12-23
一個工程中的主要方法:
public Map ky(Map map){ String url = "http://localhost:8080/api/json/ky.action"; Map reMap = new HashMap(); try{ if(map.size() == 0){ reMap.put("outResult", "0"); reMap.put("outResultReason", "無資料需要傳送"); return reMap; } map.put("typeId", "06"); ArrayList list = (ArrayList)dao.queryMapList("billVerify.getLinkUrl",map); /* if(list == null || list.size() == 0){ reMap.put("outResult", "1"); reMap.put("outResultReason", "不呼叫物流驗證介面"); return reMap; }else{ HashMap linkMap = (HashMap)list.get(0); url = linkMap.get("linkUrl").toString(); } */ HttpClient client = new HttpClient(); //返回結果集 JSONObject resJson = new JSONObject(); PostMethod postMethod = new PostMethod(url); StringPart strPart1 = new StringPart("param", URLEncoder.encode(JSONObject.fromObject(map).toString(), "utf-8")); client.getParams().setSoTimeout(15000); Part[] parts = { strPart1}; //對於MIME型別的請求,httpclient建議全用MulitPartRequestEntity進行包裝 MultipartRequestEntity mre = new MultipartRequestEntity(parts, postMethod.getParams()); postMethod.setRequestEntity(mre); //執行請求,返回狀態碼 int status = client.executeMethod(postMethod); if (status == HttpStatus.SC_OK) { String result = postMethod.getResponseBodyAsString(); resJson = JSONObject.fromObject(result); if("1".equals(resJson.get("outResult"))){ reMap.put("outResult", resJson.get("outResult")); reMap.put("outResultReason", resJson.get("outResultReason")); }else{ reMap.put("outResult", resJson.get("outResult")); reMap.put("outResultReason", resJson.get("outResultReason")); } } else { System.out.println("介面請求失敗。"); reMap.put("outResult", "0"); reMap.put("outResultReason", "請求失敗。"); } }catch(Exception e){ e.printStackTrace(); reMap.put("outResult", "0"); reMap.put("outResultReason", "請求超時。"); } return reMap; }
另一個工程中的主要方法:
public String ky(){ Map map = new HashMap(); try { jsonParam = URLDecoder.decode(param ,"UTF-8"); } catch (Exception e1) { e1.printStackTrace(); } if(jsonParam==null){ map.put("outResult", "0"); map.put("outResultReason", "引數:param 為空!"); result = JSONObject.fromObject(map); return SUCCESS; } map = jsonService.ky(jsonParam); result = JSONObject.fromObject(map); return SUCCESS; }