2008. 8. 26. 15:46
HTTP로 XML 보내기 및 결과 XML 예쁘게 보여주기 Computing에 관한 독백2008. 8. 26. 15:46
/*
* $HeadURL$
* $Revision$
* $Date$
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
import java.io.File;
import java.io.InputStream;
import java.io.StringWriter;
import javax.xml.parsers.DocumentBuilderFactory;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.FileRequestEntity;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.w3c.dom.Document;
import org.apache.xml.serialize.OutputFormat;
import org.apache.xml.serialize.XMLSerializer;
/**
*
* This is a sample application that demonstrates how to use the Jakarta
* HttpClient API.
*
* This application sends an XML document to a remote web server using HTTP POST
*
* @author Sean C. Sullivan
* @author Ortwin Glueck
* @author Oleg Kalnichevski
* @author Paul King
*/
public class PostSOAP {
/**
*
* Usage: java PostSOAP http://mywebserver:80/ SOAPAction c:\foo.xml
*
* @param args
* command line arguments Argument 0 is a URL to a web server
* Argument 1 is the SOAP Action Argument 2 is a local filename
*
*/
public static void main(String[] args) throws Exception {
boolean isBeautify = false;
if (args.length != 3 && args.length != 2) {
System.out.print("Usage: java -classpath <classpath> [-Dorg.apache.");
System.out.print("commons.logging.simplelog.defaultlog=<loglevel>] Post");
System.out.print("SOAP <url> <filename> [<soapaction>] [-beautify]\n");
System.out.print("<classpath> - must contain the commons-httpclient.jar");
System.out.print(" and commons-logging.jar\n");
System.out.print("<loglevel> - one of error, warn, info, debug, trace\n");
System.out.print("<url> - the URL to post the file to\n");
System.out.print("<filename> - file to post to the URL\n");
System.out.print("<soapaction> - the SOAP action header value");
System.out.print("(optional)\n");
System.out.println("-beautify - show pretty result(optional)\n\n");
System.exit(1);
}
// Get target URL
String strURL = args[0];
String strSoapAction = "";
if (4 == args.length) {
// Get SOAP action
strSoapAction = args[2];
if ("-beautify".equals(args[3])) {
isBeautify = true;
}
}
if (3 == args.length) {
if ("-beautify".equals(args[2])) {
isBeautify = true;
} else {
strSoapAction = args[2];
}
}
// Get file to be posted
String strXMLFilename = args[1];
File input = new File(strXMLFilename);
// Prepare HTTP post
PostMethod post = new PostMethod(strURL);
// Request content will be retrieved directly
// from the input stream
RequestEntity entity = new FileRequestEntity(input,
"text/xml; charset=ISO-8859-1");
post.setRequestEntity(entity);
// consult documentation for your web service
post.setRequestHeader("SOAPAction", strSoapAction);
// Get HTTP client
HttpClient httpclient = new HttpClient();
// Execute request
try {
int result = httpclient.executeMethod(post);
// Display status code
System.out.println("Response status code: " + result);
// Display response
System.out.println("Response body: ");
if (isBeautify) {
System.out.println(PostSOAP.beautify(post
.getResponseBodyAsStream()));
} else {
System.out.println(post.getResponseBodyAsString());
}
} finally {
// Release current connection to the connection pool once you are done
post.releaseConnection();
}
}
public static String beautify(InputStream response) {
StringWriter sFormattedXML = new StringWriter();
try {
Document oDocument = DocumentBuilderFactory.newInstance()
.newDocumentBuilder().parse(response);
OutputFormat format = new OutputFormat(oDocument, "UTF-8", true);
format.setIndent(4);
format.setIndenting(true);
format.setPreserveSpace(false);
XMLSerializer serial = new XMLSerializer(sFormattedXML, format);
serial.asDOMSerializer();
serial.serialize(oDocument.getDocumentElement());
} catch (Exception e) {
e.printStackTrace();
}
return sFormattedXML.toString();
}
}
* $HeadURL$
* $Revision$
* $Date$
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
import java.io.File;
import java.io.InputStream;
import java.io.StringWriter;
import javax.xml.parsers.DocumentBuilderFactory;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.FileRequestEntity;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.w3c.dom.Document;
import org.apache.xml.serialize.OutputFormat;
import org.apache.xml.serialize.XMLSerializer;
/**
*
* This is a sample application that demonstrates how to use the Jakarta
* HttpClient API.
*
* This application sends an XML document to a remote web server using HTTP POST
*
* @author Sean C. Sullivan
* @author Ortwin Glueck
* @author Oleg Kalnichevski
* @author Paul King
*/
public class PostSOAP {
/**
*
* Usage: java PostSOAP http://mywebserver:80/ SOAPAction c:\foo.xml
*
* @param args
* command line arguments Argument 0 is a URL to a web server
* Argument 1 is the SOAP Action Argument 2 is a local filename
*
*/
public static void main(String[] args) throws Exception {
boolean isBeautify = false;
if (args.length != 3 && args.length != 2) {
System.out.print("Usage: java -classpath <classpath> [-Dorg.apache.");
System.out.print("commons.logging.simplelog.defaultlog=<loglevel>] Post");
System.out.print("SOAP <url> <filename> [<soapaction>] [-beautify]\n");
System.out.print("<classpath> - must contain the commons-httpclient.jar");
System.out.print(" and commons-logging.jar\n");
System.out.print("<loglevel> - one of error, warn, info, debug, trace\n");
System.out.print("<url> - the URL to post the file to\n");
System.out.print("<filename> - file to post to the URL\n");
System.out.print("<soapaction> - the SOAP action header value");
System.out.print("(optional)\n");
System.out.println("-beautify - show pretty result(optional)\n\n");
System.exit(1);
}
// Get target URL
String strURL = args[0];
String strSoapAction = "";
if (4 == args.length) {
// Get SOAP action
strSoapAction = args[2];
if ("-beautify".equals(args[3])) {
isBeautify = true;
}
}
if (3 == args.length) {
if ("-beautify".equals(args[2])) {
isBeautify = true;
} else {
strSoapAction = args[2];
}
}
// Get file to be posted
String strXMLFilename = args[1];
File input = new File(strXMLFilename);
// Prepare HTTP post
PostMethod post = new PostMethod(strURL);
// Request content will be retrieved directly
// from the input stream
RequestEntity entity = new FileRequestEntity(input,
"text/xml; charset=ISO-8859-1");
post.setRequestEntity(entity);
// consult documentation for your web service
post.setRequestHeader("SOAPAction", strSoapAction);
// Get HTTP client
HttpClient httpclient = new HttpClient();
// Execute request
try {
int result = httpclient.executeMethod(post);
// Display status code
System.out.println("Response status code: " + result);
// Display response
System.out.println("Response body: ");
if (isBeautify) {
System.out.println(PostSOAP.beautify(post
.getResponseBodyAsStream()));
} else {
System.out.println(post.getResponseBodyAsString());
}
} finally {
// Release current connection to the connection pool once you are done
post.releaseConnection();
}
}
public static String beautify(InputStream response) {
StringWriter sFormattedXML = new StringWriter();
try {
Document oDocument = DocumentBuilderFactory.newInstance()
.newDocumentBuilder().parse(response);
OutputFormat format = new OutputFormat(oDocument, "UTF-8", true);
format.setIndent(4);
format.setIndenting(true);
format.setPreserveSpace(false);
XMLSerializer serial = new XMLSerializer(sFormattedXML, format);
serial.asDOMSerializer();
serial.serialize(oDocument.getDocumentElement());
} catch (Exception e) {
e.printStackTrace();
}
return sFormattedXML.toString();
}
}
Apache HTTP Client의 예제 중 하나인 PostSOAP에 XML을 예쁘게 보여주는 beautify(InputStream) method를 추가했습니다. 참고로
import org.apache.xml.serialize.OutputFormat;
import org.apache.xml.serialize.XMLSerializer;
import org.apache.xml.serialize.XMLSerializer;
이 두 import문에서의 OutputFormat, XMLSerializer의 package 이름은 IBM JDK 1.5(J9 VM이라고도 하죠)에 들어있는 Xerces의 OutputFormat이나 XMLSerializer의 package 이름을 따른 것입니다. 흔히들 많이 쓰는 Sun JDK의 Xerces는 package 구조를 Sun이 손을 댄 통에 package 이름이 다릅니다. 따라서 Sun JDK에서는 위 import문을 아래와 같이 바꾸세요.
import com.sun.org.apache.xml.internal.serialize.OutputFormat;
import com.sun.org.apache.xml.internal.serialize.XMLSerializer;