1. java調第三方介面返回XML文件用httpclient實現求大神給指示(新號就5分全給了)要一個工具類,一個用例
以下是一個http介面調用的例子:區別是返回的json數據,xml數據也是一樣的,解析下xml數據就可以了,希望對你有幫助
public String getOrderCount() {
String mobile = ServletActionContext.getRequest().getParameter("mobile");
String urlStr = "http://127.0.0.1/OderServer/orderCount.htm";
urlStr += "?telphone=" + mobile + "&endTime=" + DateUtil.getCurrentDay("yyyyMMdd") + "&timeLength=2";
URL url = null;
HttpURLConnection httpurlconnection = null;
try {
url = new URL(urlStr);
// 以post方式請求
httpurlconnection = (HttpURLConnection) url.openConnection();
httpurlconnection.setDoOutput(true);
httpurlconnection.setRequestMethod("POST");
httpurlconnection.getOutputStream().flush();
httpurlconnection.getOutputStream().close();
// 獲取響應代碼
//int code = httpurlconnection.getResponseCode();
//System.out.println("code " + code);
// 獲取頁面內容
java.io.InputStream in = httpurlconnection.getInputStream();
java.io.BufferedReader breader = new BufferedReader(
new InputStreamReader(in, "utf-8"));
StringBuffer result = new StringBuffer();
String str = breader.readLine();
while (str != null) {
result.append(str);
str = breader.readLine();
}
HttpServletResponse response = ServletActionContext.getResponse();
response.setContentType("text/json;charset=utf-8");
response.getWriter().print(result);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (httpurlconnection != null)
httpurlconnection.disconnect();
}
return null;
}
2. 如何用java語言生成xml文件,並將它返回
實例:
holen.xml
<?xml version="1.0" encoding="UTF-8"?>
<books>
<!--This is a test for dom4j, holen, 2004.9.11-->
<book show="yes">
<title>Dom4j Tutorials</title>
</book>
<book show="yes">
<title>Lucene Studing</title>
</book>
<book show="no">
<title>Lucene in Action</title>
</book>
<owner>O'Reilly</owner>
</books>
建立一個XML文檔:
/**
* 建立一個XML文檔,文檔名由輸入屬性決定
* @param filename 需建立的文件名
* @return 返回操作結果, 0表失敗, 1表成功
*/
public int createXMLFile(String filename){
/** 返回操作結果, 0表失敗, 1表成功 */
int returnValue = 0;
/** 建立document對象 */
Document document = DocumentHelper.createDocument();
/** 建立XML文檔的根books */
Element booksElement = document.addElement("books");
/** 加入一行注釋 */
booksElement.addComment("This is a test for dom4j, holen, 2004.9.11");
/** 加入第一個book節點 */
Element bookElement = booksElement.addElement("book");
/** 加入show屬性內容 */
bookElement.addAttribute("show","yes");
/** 加入title節點 */
Element titleElement = bookElement.addElement("title");
/** 為title設置內容 */
titleElement.setText("Dom4j Tutorials");
/** 類似的完成後兩個book */
bookElement = booksElement.addElement("book");
bookElement.addAttribute("show","yes");
titleElement = bookElement.addElement("title");
titleElement.setText("Lucene Studing");
bookElement = booksElement.addElement("book");
bookElement.addAttribute("show","no");
titleElement = bookElement.addElement("title");
titleElement.setText("Lucene in Action");
/** 加入owner節點 */
Element ownerElement = booksElement.addElement("owner");
ownerElement.setText("O'Reilly");
try{
/** 將document中的內容寫入文件中 */
XMLWriter writer = new XMLWriter(new FileWriter(new File(filename)));
writer.write(document);
writer.close();
/** 執行成功,需返回1 */
returnValue = 1;
}catch(Exception ex){
ex.printStackTrace();
}
return returnValue;
}
說明:
Document document = DocumentHelper.createDocument();
通過這句定義一個XML文檔對象。
Element booksElement = document.addElement("books");
通過這句定義一個XML元素,這里添加的是根節點。
Element有幾個重要的方法:
l addComment:添加註釋
l addAttribute:添加屬性
l addElement:添加子元素
3. java 解析伺服器返回的XML格式數據
public void parseXML(String filename) {
System.out.println("parse-start");
try {
System.out.println("try-catch-start");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document document = db.parse(filename);
NodeList employees = document.getChildNodes();
System.out.println("nodlist-over");
for (int i = 0; i < employees.getLength(); i++) {
Node employee = employees.item(i);
NodeList employeeInfo = employee.getChildNodes();
for (int j = 0; j < employeeInfo.getLength(); j++) {
Node node = employeeInfo.item(j);
NodeList employeeMeta = node.getChildNodes();
for (int k = 0; k < employeeMeta.getLength(); k++) {
System.out.println(employeeMeta.item(k).getNodeName()
+ ":" + employeeMeta.item(k).getTextContent());
}
}
}
System.out.println("解析完畢");
} catch (FileNotFoundException e) {
System.out.println(e.getMessage());
} catch (ParserConfigurationException e) {
System.out.println(e.getMessage());
} catch (SAXException e) {
System.out.println(e.getMessage());
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
4. 鎬庢牱浣縥ava鐨勫簲絳斾俊鎮涓鍍忓㈡埛絝榪斿洖涓涓獂ml瀵硅薄
鏂規硶涓
Servlet鏂瑰紡瑙e喅錛
import java.io.PrintWriter;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* @author 闊╁崼鍙
*/
public class TestServlet extends HttpServlet
{
private static final String CONTENT_TYPE = "text/xml; charset=UTF-8";
/**
* Updates Cart, and outputs XML representation of contents
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws java.io.IOException
{
response.setContentType(CONTENT_TYPE);
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Pragma", "no-cache");
response.setDateHeader("Expires", 0);
PrintWriter out = response.getWriter();
StringBuffer xml = new StringBuffer();
xml.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
//鍔犱笂浣犺佸彂閫佺殑xml
xml.append("");
out.write(xml.toString());
}
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws java.io.IOException
{
doPost(req, res);
}
}
ajax璇鋒眰榪欎釜Servlet,灝卞彲浠ュ緱鍒皒ml榪斿洖浜嗐
鏂規硶2錛氱洿鎺ユ妸浣犵殑xml鍐欐垚涓涓猨sp,jsp涓鍙鍐檟ml涓層
ajax鐩存帴璇鋒眰jsp灝辮兘鑾峰緱xml涓蹭簡銆
5. 怎樣在java 中調用web service 傳入參數返回xml
js 代碼
function ajaxRequest()
{
var url = "http://********.asmx";
//設置webService傳入參數
//
//注意:
//
// 調用.Net 寫的webservice(如例子中的webservicedemo.asmx)
// HelloTo(String name) 針對name參數必須寫成 <name></name>wqj,還有更多參數一樣寫,使用名稱匹配
// 傳入的參數數量可以不等於(多於或少於)方法要求的參數
//
// 調用java(xfire) 發布的webService
// 傳入的參數必須與調用方法的參數數量相等,且按傳入值的順序進行匹配
//
var para = "<name></name>wqj"; 這里應該是一個標準的xml形式,源碼貼出來時被慮掉了,請參看附件源碼
var op = {
data:para,
onComplete: showResponse,
onFailure:showError,
update:'ajaxBack'
};
var service = new WebService(url,"HelloTo",op);
service.request();
return false;
}
function showError(obj)
{
//obj 是一個xmlHttpRequest對象
alert("error");
}
function showResponse(requestText,requestXML)
{
//requestText 返回的文本
//requestXML 返回的XML
alert("ok");
}
6. java 調用cxfWebService 介面返回類型是xml格式數據顯示在jsp頁面中該如何做到
dom4j解析xml,然後把解析的數據封裝到bean里。jsp頁面上獲取bean然後顯示就行了。
和平常的從資料庫取數據,封裝後在頁面上顯示沒有區別。不過就是不去資料庫取數據,而是靠xml來取數據。
7. JAVA代碼解析方法返回的XML數據,分別取出item標簽中的值
package com;
import java.io.StringReader;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
public class TestXML {
public static void main(String[] args) {
StringBuffer sb=new StringBuffer("<data>");
sb.append("<message>");
sb.append("<status>6</status>");
sb.append("<value>識別成功</value>");
sb.append("</message>");
sb.append("<cardsinfo>");
sb.append("<card type='6'>");
sb.append("<item desc='保留'><![CDATA[輕輕巧巧]]></item>");
sb.append("<item desc='號牌號碼'><![CDATA[*888084]]></item>");
sb.append("</card>");
sb.append("</cardsinfo>");
sb.append("</data>");
try {
DocumentBuilderFactory factory = DocumentBuilderFactory
.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder
.parse(new InputSource((new StringReader(sb.toString()))));
NodeList list = doc.getElementsByTagName("item");
System.out.println("------------節點item如下:------------");
for (int i = 0; i < list.getLength(); i++) {
Node book = list.item(i);
System.out.println("\t節點=" + i + "\t內容="
+ book.getFirstChild().getNodeValue());
}
System.out.println("------------結束------------");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
8. java如何使sql查詢的數據返回xml格式
你想輸出什麼樣的XML格式
String s=null;
while(rs.next()){
s+=(rs.getString("member")+rs.getString("content"));
}
out.print(s);
修改成:
out.println("<?xml version=\"1.0\" encoding=\"gbk\"?>");
out.println("<XmlMembers>");
while(rs.next()){
out.println("<XmlMember>");
out.println("<member><![CDATA[");
out.println(rs.getString("member"));
out.println("]]</member>");
out.println("<content><![CDATA[");
out.println(rs.getString("content"));
out.println("]]</content>");
out.println("</XmlMember>");
}
out.println("</XmlMembers>");
rs.close();
9. JAVA以POST方式提交XML獲取返回值(返回格式為XML)
URL url = new URL(requestUrl);
HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();
httpUrlConn.setRequestMethod(「POST」);
OutputStream outputStream = httpUrlConn.getOutputStream();
outputStream.write(xml);
outputStream.close();
InputStream inputStream = httpUrlConn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String str = null;
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
bufferedReader.close();
inputStreamReader.close();
// 釋放資源
inputStream.close();
inputStream = null;
httpUrlConn.disconnect();