客户端请求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>12345678@ott</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);
}