HTTP介面POST方式呼叫例項
客戶端請求HTTP介面(POST):
方法一:
String url ="http://IP:埠/usi-sep/services/SqmScapService?wsdl";//請求介面地址
URL wsUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection) wsUrl.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setConnectTimeout(5*1000);
conn.setRequestProperty("Content-Type", "text/xml;charset=UTF-8");
conn.setRequestProperty("SOAPAction",
url);
String req = "<soapenv:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:sqm=\"http://www.chinatelecom.com/oss/sqmws/services/SqmService\">";//名稱空間
req+="<soapenv:Header>";
req+="<Esb>";
req+="<Route>";
req+="<EsbId/>";
req+="</Route>";
req+="<Business/>";
req+="</Esb></soapenv:Header>";
req+="<soapenv:Body>";
req+="<sqm:platformQry soapenv:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">";//platformQry方法名
req+="<xmlInfo xsi:type=\"soapenc:string\" xmlns:soapenc=\"http://schemas.xmlsoap.org/soap/encoding/\"><![CDATA[" ;
req+="<root>";
req+="<interfaceCode>IPTV_zzyw_select</interfaceCode>";
req+="<queryInfo>"; // <!--查詢條件資訊-->
req+="<attrInfo>"; // <!--查詢屬性資訊-->
req+="<attrCode>iptv_num</attrCode>"; // <!--屬性編碼-->
req+="<attrValue>[email protected]</attrValue>"; //<!--屬性編碼 -->
req+="</attrInfo>";
req+="</queryInfo>";
req+="</root>";
req+="]]></xmlInfo>";
req+="</sqm:platformQry>";
req+="</soapenv:Body>";
req+="</soapenv:Envelope>";
PrintStream ps = new PrintStream(conn.getOutputStream(),true,"utf-8");
ps.print(req);
ps.close();
BufferedReader bReader = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"));
String line, resultStr = "";
while (null != (line = bReader.readLine())) {
resultStr += line;
}
bReader.close();
String xml =StringEscapeUtils.unescapeXml(resultStr);//把xml還原
/***********************************************開始解析xml報文*******************************************/
Map map;
try {
map = CommonService.parseXmlToMap(xml);//見其他commonService檔案
System.out.println("返回解析xml"+map);
List response =(List) map.get("response");
String result = (String) ((Map)response.get(0)).get("result");
String desc = (String) ((Map)response.get(0)).get("desc");//返回資訊
List record =(List) map.get("record");
for(int i=0;i<record.size();i++){
String ZD = (String) ((Map)record.get(i)).get("ZD");
String TYPE = (String) ((Map)record.get(i)).get("TYPE");
String IPTV_NUM = (String) ((Map)record.get(i)).get("IPTV_NUM");
String BEGINTIME = (String) ((Map)record.get(i)).get("BEGINTIME");
String CONTENTNAME = (String) ((Map)record.get(i)).get("CONTENTNAME");
System.out.println("******************************************"+i+"***********************************");
System.out.println("ZD++++:"+ZD);
System.out.println("TYPE++++:"+TYPE);
System.out.println("IPTV_NUM++++:"+IPTV_NUM);
System.out.println("BEGINTIME++++:"+BEGINTIME);
System.out.println("CONTENTNAME++++:"+CONTENTNAME);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
CommonService:
package ceshi;
import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; import java.sql.SQLException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.logging.Logger;
import org.dom4j.Document; import org.dom4j.DocumentHelper; import org.dom4j.Element;
import javax.servlet.http.HttpServletRequest; import javax.xml.namespace.QName;
import org.apache.axis.client.Call; import org.apache.axis.client.Service; import org.apache.axis.description.OperationDesc; import org.apache.axis.description.ParameterDesc;
/** * 公共處理及資訊分享類 能夠考慮每個方法傳sqlMap,改用私有靜態sqlMap * * @author luobin * */ public class CommonService {
/** * 把源目標字串去空格操作 * * @param target:傳遞字串 * @return */ public static String trimStr(String target) { if (target != null && target.length() > 0) { return target.trim(); } else { return ""; } }
/** * 把得到的具體分鐘數轉化為小時和分鐘的形式(針對minute是正整數情況) * * @param minute * 具體分鐘數(>0) * @return */ public static String convertTime(String minute) { int getMinute = Integer.parseInt(minute); int hh = getMinute / 60; int mi = getMinute % 60 == 0 ? 1 : getMinute % 60; return hh > 0 ? hh + "小時" + mi + "分鐘前" : mi + "分鐘前"; }
/** * * @param map 解析返回報文的結果集 * @return * 解析返回報文結果集,判斷是否呼叫成功 */ public static List getErrorMsg(Map map){ List tempList=(ArrayList)map.get("RETURN_INFO"); if(tempList==null){ tempList = new ArrayList(); tempList.add(new HashMap().put("RETURN_MSG", "返回結果為空")); } return tempList; } /** * 解析xml * * @param Xml * 呼叫服務返回的報文 * @return Map 結果集 * @throws Exception */ public static Map parseXmlToMap(String xml) throws Exception { if (xml == null || "".equals(xml)) { return new HashMap(); } Map resultMap = new HashMap(); parseXmlToList(parseText(xml).getRootElement(), resultMap); return resultMap; }
/** * 解析字串為Document * * @param text * @return * @throws Exception */ public static Document parseText(String text) throws Exception { if (text == null) { throw new IllegalArgumentException("解析串為NULL!"); } Document document = null; try { document = DocumentHelper.parseText(text); } catch (Exception e) { e.printStackTrace(); } if (document == null) { throw new IllegalArgumentException("XML格式不對!"); } return document; }
/** * 迭代解析返回報文 * * @param element * xml元素 * @param resultMap * 結果集 * @return * @throws Exception */ public static List parseXmlToList(Element element, Map resultMap) throws Exception { List resultList = new ArrayList(); Map tempMap = new HashMap(); if (resultMap.size() == 0) { resultMap.put("RETURN_INFO", resultList); } for (Iterator ie = element.elementIterator(); ie.hasNext();) { Element tempElemnt = (Element) ie.next(); // 判斷該節點下是否有子節點 if (tempElemnt.elementIterator().hasNext()) { // 得到該節點的名稱 String nodeName = tempElemnt.getName(); // 判斷返回結果map中有沒有該節點名稱的key if (!resultMap.containsKey(nodeName)) { // 新增該節點名稱作為key遞迴這層節點內容作為value resultMap.put(nodeName, parseXmlToList(tempElemnt, resultMap)); } else { // 取出返回結果map中該節點下的內容 List list2 = (ArrayList) resultMap.get(nodeName); // 舊的內容歸併新的該節點下的遞迴內容 list2.addAll(parseXmlToList(tempElemnt, resultMap)); // 將結果儲存到返回結果中 resultMap.put(nodeName, list2); } } else { // 沒有子節點直接新增該節點內容 // tempList.add(tempElemnt.getText().trim()); tempMap.put(tempElemnt.getName(), tempElemnt.getText().trim()); } } resultList.add(tempMap); return resultList; } /** * * @param map * 解析返回報文的結果集 * @return 解析返回報文結果集,判斷是否呼叫成功 */ public static boolean judgeReturn(Map map) { List tempList = (ArrayList) map.get("RETURN_INFO"); if (tempList == null) { return false; } Map resultMap = (HashMap) tempList.get(0); return "0".equals(resultMap.get("RETURN_CODE")); } /** * * @param map * 解析返回報文的結果集 * @param father * 父節點 eg:Response * @param father * 子節點 eg:RspCode * @param judgeFlag * 判斷標識 eg:0000 * @return 解析返回報文結果集,判斷是否呼叫成功 */ public static boolean isSuccess(Map map,String father,String child,String judgeFlag) { List tempList = (ArrayList) map.get(father); if (tempList == null) { return false; } Map resultMap = (HashMap) tempList.get(0); return judgeFlag.equals(resultMap.get(child)); } /** * * @param map * 解析返回報文的結果集 * @param father * 父節點 eg:Response * @param father * 子節點 eg:RspCode * @param returnMsg * 返回資訊 eg:號碼不存在 * @return * 解析錯誤結果集通用方法 */ public static String getErrorMsgCommon(Map map,String father,String child,String returnMsg){ List tempList=(ArrayList)map.get(father); if(tempList==null){ return "返回結果為空!"; } Map commonMap = (Map)tempList.get(0); return (String)commonMap.get(returnMsg); } }
方法二:
/**
*
* @Title: xiaowoqury
* @author:malz
* @date: 2018-9-13下午5:22:42
* @Description:
*/
public String xiaowoqury(String userId,String page){
String resultString = "";
String url = "http://IP:埠/orderSd";//測試
CloseableHttpClient client = HttpClientBuilder.create().build();
HttpPost post = new HttpPost(url);
String sign="112345";
List<NameValuePair> list =new ArrayList();
list.add(new BasicNameValuePair("userId", userId));
list.add(new BasicNameValuePair("page", page));
list.add(new BasicNameValuePair("size", "10"));
list.add(new BasicNameValuePair("sign", sign));
try {
post.setEntity(new UrlEncodedFormEntity(list));
CloseableHttpResponse response;
response = client.execute(post);
resultString=EntityUtils.toString(response.getEntity());
HttpClientUtils.closeQuietly(response);
System.out.println("介面返回資訊"+resultString);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return resultString;
}
例:
客戶端:
public String quryInterface(String sign,String userId,String page){
String resultString="";
String url = "http://IP:埠/Tvinterface/servlet/tvInterface";//介面地址
CloseableHttpClient client = HttpClientBuilder.create().build();
HttpPost post = new HttpPost(url);
List<NameValuePair> list =new ArrayList();
// List<NameValuePair> list = new ArrayList<>();
list.add(new BasicNameValuePair("sign",sign));
list.add(new BasicNameValuePair("userId",userId));
list.add(new BasicNameValuePair("page",page));
try {
post.setEntity(new UrlEncodedFormEntity(list));
CloseableHttpResponse response;
response = client.execute(post);
resultString=EntityUtils.toString(response.getEntity());
HttpClientUtils.closeQuietly(response);
System.out.println("介面返回"+resultString);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return resultString;
}
服務端:(servlet介面)
右鍵--新建--Servlet
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=utf-8");
String result = "";
System.out.println(request);
String sign = request.getParameter("sign");
String userId = request.getParameter("userId");
String page = request.getParameter("page"); //頁數
TvAppreciation tv = new TvAppreciation();
if("1".equals(sign)){
String xiaowoInfo=tv.xiaowoqury(userId, page);
response.getWriter().print(xiaowoInfo);
}else if("2".equals(sign)){
String tvinfo = tv.post(userId);
response.getWriter().print(tvinfo);
}