Issue invoking web service within websphere 6.1 environment - web-services

I'm trying to invoke a SOAP web service from within WebSphere 6.1. I can run the code fine using Apache Tomcat 6.0.36 runtime. However, with WebSphere 6.1, I get the following error:
Jan 5, 2015 7:19:23 PM com.ibm.ws.ssl.config.SSLConfigManager INFO:ssl.disable.url.hostname.verification.CWPKI0027I
Jan 5, 2015 7:19:24 PM com.ibm.ws.channel.framework.impl.WSChannelFrameworkImpl AUDIT: chain.started
Jan 5, 2015 7:19:25 PM com.ibm.ws.webservices.engine.PivotHandlerWrapper invoke WARNING:
WSWS3734W: Warning: Exception caught from invocation to com.ibm.ws.webservices.engine.transport.http.HTTPSender:
WebServicesFault faultCode:
HTTP faultString: ( 401 ) Unauthorized faultActor: http://server.customer.com:80
faultDetail: null:
WSWS3192E: Error: return code: ( 401 ) Unauthorized
Here's the code I'm running, which works fine in Apache Tomcat:
public class Test {
public void submitOrder()
{
try {
// Create SOAP Connection
SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
SOAPConnection soapConnection = soapConnectionFactory.createConnection();
// Send SOAP Message to SOAP Server
String url = "http://server.customer.com/serviceEndpoint";
SOAPMessage soapResponse = soapConnection.call(createSOAPRequest(), url);
// Process the SOAP Response
printSOAPResponse(soapResponse);
soapConnection.close();
} catch (Exception e) {
System.err.println("Error occurred while sending SOAP Request to Server");
e.printStackTrace();
}
}
private static SOAPMessage createSOAPRequest() throws Exception {
MessageFactory messageFactory = MessageFactory.newInstance();
SOAPMessage soapMessage = messageFactory.createMessage();
MimeHeaders hd = soapMessage.getMimeHeaders();
String username = "xxxxx";
String password = "xxxxx";
byte [] auth = (username+":"+password).getBytes();
String authorization = new String ( Base64.encodeBase64(auth) );
System.out.println ( "authorization = " + authorization );
hd.addHeader("Authorization", "Basic " + authorization);
SOAPPart soapPart = soapMessage.getSOAPPart();
// SOAP Envelope
SOAPEnvelope envelope = soapPart.getEnvelope();
// SOAP Body
SOAPBody soapBody = envelope.getBody();
SOAPElement ordersElem = soapBody.addChildElement("Orders");
// Need to add two attributes to this node!
SOAPElement orderElem = ordersElem.addChildElement("Order");
Name codeAttributeName = envelope.createName("code");
orderElem.addAttribute(codeAttributeName, "00001");
Name timeAttributeName = envelope.createName("time");
orderElem.addAttribute(timeAttributeName, "2015-01-04 12:00:00 PM");
SOAPElement salesOrderConfElem = orderElem.addChildElement("SalesOrderConfirmationCode");
salesOrderConfElem.addTextNode("16041");
SOAPElement statusElem = orderElem.addChildElement("Status");
Name statusCodeAttributeName = envelope.createName("code");
statusElem.addAttribute(statusCodeAttributeName, "COMPLETE");
SOAPElement entriesElem = orderElem.addChildElement("Entries");
SOAPElement entryElem = entriesElem.addChildElement("Entry");
SOAPElement entryNumElem = entryElem.addChildElement("EntryNumber");
entryNumElem.addTextNode("1");
SOAPElement productElem = entryElem.addChildElement("ProductCode");
productElem.addTextNode("738053571");
SOAPElement qtyElem = entryElem.addChildElement("Quantity");
qtyElem.addTextNode("1");
SOAPElement shippedElem = entryElem.addChildElement("Shipped");
shippedElem.addTextNode("1");
SOAPElement backOrderElem = entryElem.addChildElement("Backordered");
backOrderElem.addTextNode("1");
MimeHeaders headers = soapMessage.getMimeHeaders();
headers.addHeader("SOAPAction", "http://sap.com/xi/WebService/soap1.1");
soapMessage.saveChanges();
/* Print the request message */
System.out.print("Request SOAP Message = ");
soapMessage.writeTo(System.out);
System.out.println();
return soapMessage;
}
/**
* Method used to print the SOAP Response
*/
private static void printSOAPResponse(SOAPMessage soapResponse) throws Exception {
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
Source sourceContent = soapResponse.getSOAPPart().getContent();
System.out.print("\nResponse SOAP Message = ");
StreamResult result = new StreamResult(System.out);
transformer.transform(sourceContent, result);
}
/**
* #param args
*/
public static void main(String[] args) {
Test t = new Test();
t.submitOrder();
}
}
CORRECTION: the SOAP envelopes being created by Tomcat and WebSphere are not the same. Tomcat, using Java 1.6, creates the following:
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
<SOAP-ENV:Header/>
<SOAP-ENV:Body>
<Orders>
while WebSphere, using IBM's version of 1.5, creates the following:
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<soapenv:Header/>
<soapenv:Body>
<Orders>
How would I get WebSphere to create the same SOAP envelop as Tomcat?

Related

com.sun.xml.messaging.saaj.SOAPExceptionImpl: Invalid Content-Type:text/html. Is this an error message instead of a SOAP response?

I am consuming SOAP service where sending request to soap url and getting the response. But when i try to connect using WebServiceTemplate getting a nested exception as
com.sun.xml.messaging.saaj.SOAPExceptionImpl: Invalid Content-Type:text/html. Is this an error message instead of a SOAP response?
Below is the code where i am sending the request to soap client
soapClient.sendEmail(request); - From the service to soap client
Below is the soap client code to connect and send the request
#Service
public class SoapClient {
#Autowired
private Jaxb2Marshaller marshaller;
private WebServiceTemplate template;
#Value("${email.url}")
String emailUrl;
#Value("${email.vaultQuery}")
String querytaken;
#Value("${email.valtQu}")
String queryp;
public MessageResponse sendEmail(MessageRequest request) {
template = new WebServiceTemplate(marshaller);
String plainCredentials = querytaken + ":" + queryp;
String base64Credentials = new String(Base64.encodeBase64(plainCredentials.getBytes()));
return (MessageResponse) template.marshalSendAndReceive(emailUrl, request,new WebServiceMessageCallback() {
public void doWithMessage(WebServiceMessage message) throws IOException {
TransportContext context = TransportContextHolder.getTransportContext();
HttpUrlConnection connection = (HttpUrlConnection) context.getConnection();
connection.getConnection().setRequestProperty("Authorization", "Basic " + base64Credentials);
}
});
}
}
Can anyone help me out for my issue

Using Httpclient for send SOAP request In Asp.net Core

Im using Asp.net Core, for calling an asmx service which has 4 methods and i want to call one of them by the name: Verify method, i do this steps:
1-Create realted SOAP:
private XmlDocument CreateSoapEnvelope(PayVM payModel)
{
XmlDocument soapEnvelop = new XmlDocument();
string requiredXML = string.Format(#"<SOAP-ENV:Envelope xmlns:SOAP-ENV=""http://schemas.xmlsoap.org/soap/envelope/"" xmlns:xsi=""http://www.w3.org/1999/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/1999/XMLSchema""><SOAP-ENV:Body><verifyTransaction xmlns=""http://tempuri.org/""> <String_1 xsi:type=""xsd:string"">{0}</String_1><String_2 xsi:type=""xsd:string"">{1}</String_2></verifyTransaction></SOAP-ENV:Body></SOAP-ENV:Envelope>", payModel.ReNO, payModel.MID);
soapEnvelop.LoadXml(requiredXML);
return soapEnvelop;
}
2-create the HttpClient and send my request:
XmlDocument soapRequest = CreateSoapEnvelope(iPGVerifyResultModel);
using (var client = new HttpClient())
{
var request = new HttpRequestMessage()
{
RequestUri = new Uri("relatedUri/ServiceName.asmx"),
Method = HttpMethod.Post
};
request.Content = new StringContent(soapRequest.ToString(), Encoding.UTF8, "text/xml");
request.Headers.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/xml"));
request.Content.Headers.ContentType = new MediaTypeHeaderValue("text/xml");
request.Headers.Add("SOAPAction", "Verify"); //I want to call this method
HttpResponseMessage response = client.SendAsync(request).Result;
if (!response.IsSuccessStatusCode)
{
throw new Exception();
}
Task<Stream> streamTask = response.Content.ReadAsStreamAsync();
Stream stream = streamTask.Result;
var sr = new StreamReader(stream);
var soapResponse = XDocument.Load(sr);
//do some other stuff...
}
but i didn't result, i try uses service by same parameters with Soap UI and the service work properly, but in my way i got StatusCode: 400 what is the problem?

How to replace response body in WSO2 API Manager 1.10.0 Custom Handler

I have written a CustomHandler which verifies if there is a specific key in the request. If the key is missing, handler should send back response to the client with the text saying that the key is missing. When a get request is sent to the server without key in the header, server responds back to the client with the modified payload. But, when a post request is sent to server, it sends back the original payload sent by the client. Below is the code that sends back response to the client with modified payload.
private void handleAuthenticationFailure(MessageContext messageContext, APISecurityException e){
SOAPBody body = messageContext.getEnvelope().getBody();
for (Iterator itr = body.getChildElements(); itr.hasNext();) {
OMElement child = (OMElement) itr.next();
child.detach();
}
org.apache.axis2.context.MessageContext axis2MC = ((Axis2MessageContext) messageContext).
getAxis2MessageContext();
axis2MC.setProperty(Constants.Configuration.CONTENT_TYPE, "application/xml");
axis2MC.removeProperty("NO_ENTITY_BODY");
axis2MC.setProperty("HTTP_SC", HttpStatus.SC_UNAUTHORIZED);
messageContext.setResponse(true);
messageContext.setProperty("RESPONSE", "true");
messageContext.setTo(null);
messageContext.getEnvelope().getBody().addChild(getFaultPayload(e));
Axis2Sender.sendBack(messageContext);
}
private OMElement getFaultPayload(APISecurityException e) {
OMFactory fac = OMAbstractFactory.getOMFactory();
OMNamespace ns = fac.createOMNamespace(APISecurityConstants.API_SECURITY_NS,
APISecurityConstants.API_SECURITY_NS_PREFIX);
OMElement payload = fac.createOMElement("fault", ns);
OMElement errorCode = fac.createOMElement("code", ns);
errorCode.setText(String.valueOf(e.getErrorCode()));
OMElement errorMessage = fac.createOMElement("message", ns);
errorMessage.setText("Missing Credentials");
OMElement errorDetail = fac.createOMElement("description", ns);
errorDetail.setText(e.getMessage());
payload.addChild(errorCode);
payload.addChild(errorMessage);
payload.addChild(errorDetail);
return payload;
}
Am I missing something ? How do I drop the original payload of the post request and send back the modified payload ? Thanks for any help.
We had a similar requirement: replacing an arbitrary string within the body payload of an HTTP response. We achieved this through custom mediation, but the approach should be equally valid through a handler.
We avoided using XML parsing, construction, and injection by using synapse JsonUtil (org.apache.synapse.commons.json.JsonUtil), specifically String jsonResponse = JsonUtil.jsonPayloadToString(axis2) to read the payload body and JsonUtil.newJsonPayload(axis2, jsonResponse, true, true) to write.
If you require the payload to be in XML, you'll want to look at Utils.setFaultPayload and Utils.sendFault, which can be found in their org.wso2.carbon.apimgt.gateway.handlers package at https://github.com/wso2/carbon-apimgt/blob/master/components/apimgt/org.wso2.carbon.apimgt.gateway/src/main/java/org/wso2/carbon/apimgt/gateway/handlers/Utils.java.
public static void setFaultPayload(MessageContext messageContext, OMElement payload) {
org.apache.axis2.context.MessageContext axis2MC = ((Axis2MessageContext) messageContext).
getAxis2MessageContext();
JsonUtil.removeJsonPayload(axis2MC);
messageContext.getEnvelope().getBody().addChild(payload);
Map headers = (Map) axis2MC.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS);
String acceptType = (String) headers.get(HttpHeaders.ACCEPT);
//If an Accept header has been provided.
if(!StringUtils.isEmpty(acceptType) && !"*/*".equals(acceptType)){
axis2MC.setProperty(Constants.Configuration.MESSAGE_TYPE, acceptType);
}
}
public static void sendFault(MessageContext messageContext, int status) {
org.apache.axis2.context.MessageContext axis2MC = ((Axis2MessageContext) messageContext).
getAxis2MessageContext();
axis2MC.setProperty(NhttpConstants.HTTP_SC, status);
messageContext.setResponse(true);
messageContext.setProperty("RESPONSE", "true");
messageContext.setTo(null);
axis2MC.removeProperty("NO_ENTITY_BODY");
// Always remove the ContentType - Let the formatter do its thing
axis2MC.removeProperty(Constants.Configuration.CONTENT_TYPE);
Map headers = (Map) axis2MC.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS);
if (headers != null) {
headers.remove(HttpHeaders.AUTHORIZATION);
headers.remove(HttpHeaders.AUTHORIZATION);
headers.remove(HttpHeaders.HOST);
}
Axis2Sender.sendBack(messageContext);
}

Customize SOAP request send from Windows 8 application

I am consuming a WSDL in a Windows 8 app. I need to customize the SOAP request like
New SOAP Request:
</ns0:Header>
<ns0:Body>
<ns0:Request xmlns:ns0="http://www.ABC.co.il/2004/01/RetrieveEntityDetails/EntityDetailsRequest">
</ns0:Request></ns0:Body></ns0:Envelope>
Current SOAP Request:
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
<s:Header>
</s:Header>
<s:Body>
<RetrieveEntityDetailsXPOP_XmlRequest xmlns="http://tempuri.org/">
<RetrieveEntityDetailsXPOP_Xml xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<requestDoc>
</requestDoc>
</RetrieveEntityDetailsXPOP_Xml>
</RetrieveEntityDetailsXPOP_XmlRequest>
</s:Body>
</s:Envelope>
How will I change the namespace and set a request tag inside the body tag.
Code:
Client = new EAI_RetrieveEntityDetailsXP_ServiceSoapClient();
Client.RetrieveEntityDetailsXPOP_XmlCompleted += Client_RetrieveEntityDetailsXPOP_XmlCompleted;
XElement requestData = GetRequestData();
using (new OperationContextScope(Client.InnerChannel))
{
// Create a custom soap header
var msgHeader = MessageHeader.CreateHeader("myCustomHeader", string.Empty, "myValue");
// Add the header into request message
OperationContext.Current.OutgoingMessageHeaders.Add(msgHeader);
Client.RetrieveEntityDetailsXPOP_XmlAsync(requestData);
}
I have actually used HttpCleint to call this service by using following code. Using this we can generate the SOAP request as desired.
string soapString = ConstructSoapRequest();
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Add("SOAPAction", SOAPActionUri);
var content = new StringContent(soapString, Encoding.UTF8, "text/xml");
using (var response = await client.PostAsync(Uri, content))
{
var soapResponse = await response.Content.ReadAsStringAsync();
return soapResponse;
}
}
private string ConstructSoapRequest()
{
return String.Format(#"<ns0:Envelope xmlns:ns0='http://www.cellcom.co.il/2004/01/std-headers'>
<ns0:Header>
</ns0:Header>
<ns0:Body>
<ns0:Request xmlns:ns0='http://www.cellcom.co.il/2004/01/RetrieveEntityDetails/EntityDetailsRequest'>
</ns0:Request></ns0:Body></ns0:Envelope>", 100);
}

SOAPConnection not handling gzip response

I am using SOAPConnection to to invoke a SOAP based web service. The request is sent with "Accept-Encoding: gzip,deflate" in the header.
I used fiddler to grab the response, it is gzipped compressed, but while deserializing the message, the SOAPConnection is giving an error saying "invalid utf-8" message.
I tried normal http post and the http response is able to unzip the response correctly. Do I need to set some attributes on SOAPConnection to get it to handle the gzip message?
I found this snippet doing the job
SOAPMessage response = conn.call(finalRequest, aUrl);
// The response is gzip encoded, so decompress the response.
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.writeTo(out);
byte[] barr = out.toByteArray();
InputStream gzipStream = new GZIPInputStream(new ByteArrayInputStream(barr));
Reader decoder = new InputStreamReader(gzipStream, "UTF-8");
BufferedReader buffered = new BufferedReader(decoder);
int n = 0;
char[] cbuf = new char[1024];
Writer w = new StringWriter();
while ((n = buffered.read(cbuf)) != -1) {
w.write(cbuf,0,n);
}
// the writer now contains unzipped message.
System.out.println(w.toString());
GZIP Request,Response form Server:
If the server is enable with GZip then the server sends gzip-compress text data. For this we need over a request with Http headers as:
Request: We must send a HTTP request containing the Accept-Encoding: gzip header.
Response: If gzip is enabled, the server should return the Content-Encoding: gzip header.
Soap WebServies:
a - Grahical Weather Endpoint HTTPS and its WSDL URL OnlineClient
Response Headers:
Content-Type:text/xml; charset=ISO-8859-1
Vary:Accept-Encoding
Content-Encoding:gzip
Plain Response - DemoOnline Webserice HTTP. for example see stackpostResponse Headers: Content-Type:application/soap+xml; charset=utf-8
Request the WebService using SOAPConnectiona and get response in GZIP compressed format:
public static String getGZIP(byte[] zipBytes) {
try {
GZIPInputStream gzipInput = new GZIPInputStream( new ByteArrayInputStream(zipBytes) );
return IOUtils.toString(gzipInput);
} catch (IOException e) {
throw new UncheckedIOException("Error while decompression!", e);
}
}
public static void getSOAPConnection(SOAPMessage soapMsg) throws Exception {
System.out.println("\n===== SOAPConnection =====");
MimeHeaders headers = soapMsg.getMimeHeaders();
headers.addHeader("SoapBinding", serverDetails.get("SoapBinding") );
headers.addHeader("MethodName", serverDetails.get("MethodName") );
headers.addHeader("SOAPAction", serverDetails.get("SOAPAction") );
headers.addHeader("Content-Type", serverDetails.get("Content-Type")); // InBound
headers.addHeader("Accept-Encoding", serverDetails.get("Accept-Encoding")); // OutBound
if (soapMsg.saveRequired()) soapMsg.saveChanges();
/*SOAPMessage message = MessageFactory.newInstance().createMessage(headers, new ByteArrayInputStream(TSOXML.getBytes()));*/
SOAPConnectionFactory newInstance = SOAPConnectionFactory.newInstance();
javax.xml.soap.SOAPConnection connection = newInstance.createConnection();
SOAPMessage resp = connection.call(soapMsg, getURL( serverDetails.get("SoapServerURI") ));
MimeHeaders mimeHeaders = resp.getMimeHeaders();
String[] header = mimeHeaders.getHeader("Content-Encoding");
String contentEoncoding = "";
if (header != null && header.length > 0) contentEoncoding = header[0].toString();
System.out.println("Content:"+contentEoncoding);
if (contentEoncoding.equalsIgnoreCase("GZIP")) {
System.out.println("SOAP Message in GZIP");
ByteArrayOutputStream out = new ByteArrayOutputStream();
resp.writeTo(out);
byte[] zipBytes = out.toByteArray();
String gZipString= getGZIP(zipBytes);
System.out.println("Response:"+ gZipString);
SOAPMessage soapMessage = getSOAPMessagefromDataXML(gZipString);
System.out.println("SOAP Message Object:\n"+soapMessage);
getSOAPXMLasString(soapMessage);
} else {
getSOAPXMLasString(resp);
}
}
Requesting SOAP WS using HTTPCline. The way SOAPUI requests:
public static void getHttpURLConnection_Core(SOAPMessage soapMsg) throws Exception {
System.out.println("\n===== java.net.HttpURLConnection =====");
URL url = new URL(null, serverDetails.get("SoapServerURI"));
String protocol = url.getProtocol();
System.out.println("Protocol: "+protocol);
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(PROXY_ADDRESS, PROXY_PORT));
HttpURLConnection connection = (HttpURLConnection) url.openConnection(proxy);
connection.setReadTimeout(5 * 1000);
connection.setConnectTimeout(5 * 1000);
connection.setDoInput(true); connection.setDoOutput(true); connection.setUseCaches(true);
//String authString = username + ":" + password; // Authorization: Basic ZW9uMDE5XzAxOkVsaWFfMTIz
//String authMsg = "Basic " + Base64.encode(authString.getBytes());
//connection.setRequestProperty(javax.ws.rs.core.HttpHeaders.AUTHORIZATION, authMsg);
((HttpURLConnection) connection).setRequestMethod("POST");
connection.setRequestProperty(javax.ws.rs.core.HttpHeaders.ACCEPT, "text/xml");
connection.setRequestProperty(javax.ws.rs.core.HttpHeaders.ACCEPT_LANGUAGE, "en-US,en;q=0.9");
connection.setRequestProperty("MethodName", serverDetails.get("MethodName") );
connection.setRequestProperty("SOAPAction", serverDetails.get("SOAPAction") );
connection.setRequestProperty("HTTP_ACCEPT_ENCODING", "gzip, deflate, br");
connection.setRequestProperty("Accept-Encoding", serverDetails.get("Accept-Encoding"));
String soapxmLasString = getSOAPXMLasString(soapMsg);
connection.setRequestProperty(javax.ws.rs.core.HttpHeaders.CONTENT_TYPE, "text/xml");// serverDetails.get("Content-Type")
connection.setRequestProperty( "Content-Length", String.valueOf(soapxmLasString.length()));
DataOutputStream dataOutputStream = new DataOutputStream(connection.getOutputStream());
try {
dataOutputStream.writeBytes(soapxmLasString);
} finally {
dataOutputStream.close();
}
long start = System.currentTimeMillis();
long end = System.currentTimeMillis();
String date = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(Calendar.getInstance().getTime());
System.out.println("TIme taken Date:"+date+", Time:"+ (end-start));
String contentEncoding = connection.getContentEncoding();
System.out.println("Encoding:"+ contentEncoding);
int responseCode = connection.getResponseCode();
String responseMessage = connection.getResponseMessage();
System.out.println("Response Code: " + responseCode + " " + responseMessage);
String xmlRply = null ;
String requestStatus = "Fail";
if (responseCode == HttpURLConnection.HTTP_OK) {
requestStatus = "Pass";
InputStream inputStream = connection.getInputStream();
xmlRply = getStreamContent(inputStream, contentEncoding);
} else { // Response Code: 500 Internal Server Error
InputStream errorStream = connection.getErrorStream();
xmlRply = getStreamContent(errorStream, contentEncoding);
}
System.out.println("Reply: " + xmlRply);
System.out.println("Request Status:"+ requestStatus);
}
public static String getStreamContent(InputStream input, String encoding) throws IOException {
byte[] httpRply;
String rply;
httpRply = IOUtils.toByteArray(input);
System.out.println("Byte Array:"+httpRply.toString());
if (encoding == null) {
rply = new String(httpRply);
} else if ( encoding.equalsIgnoreCase("GZIP") ) {
rply = getGZIP(httpRply);
} else { // "ISO-8859-1", ";TF-8"
rply = new String(httpRply, encoding);
}
return rply;
}
Working example where the Server response with GZIP format.
public class SOAP_Weather {
static final String PROXY_ADDRESS = "Proxy_*****.net";
static final int PROXY_PORT = 9400;
static HashMap<String, String> serverDetails = new HashMap<>();
static {
// https://graphical.weather.gov/xml/ : conus
serverDetails.put("SoapServerURI", "https://graphical.weather.gov:443/xml/SOAP_server/ndfdXMLserver.php");
serverDetails.put("SoapWSDL", "https://graphical.weather.gov/xml/SOAP_server/ndfdXMLserver.php?wsdl");
serverDetails.put("SoapXML", "<ndf:CornerPoints xmlns:ndf=\"https://graphical.weather.gov/xml/DWMLgen/wsdl/ndfdXML.wsdl\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"><sector xsi:type=\"xsd:string\">conus</sector></ndf:CornerPoints>");
serverDetails.put("SoapBinding", "ndfdXMLBinding");
serverDetails.put("MethodName", "CornerPoints");
serverDetails.put("SOAPAction", "https://graphical.weather.gov/xml/DWMLgen/wsdl/ndfdXML.wsdl#CornerPoints");
serverDetails.put("User-Agent", "Apache-HttpClient");
serverDetails.put("Accept-Encoding", "gzip,deflate,sdch");
serverDetails.put("Content-Type", "text/xml;charset=UTF-8");
}
public static void main(String[] args) throws Exception {
callSoapService();
}
public static void callSoapService( ) throws Exception{
String xmlData = serverDetails.get("SoapXML");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
dbFactory.setNamespaceAware(true);
dbFactory.setIgnoringComments(true);
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
InputSource ips = new org.xml.sax.InputSource(new StringReader(xmlData));
Document docBody = dBuilder.parse(ips);
//docBody.createElementNS(DSIG_NS, "ds");
System.out.println("Data Document: "+docBody.getDocumentElement());
// Protocol 1.1=SOAP-ENV Content-Type:text/xml; charset=utf-8, 1.2=env Content-Type:application/soap+xml; charset=utf-8
MessageFactory messageFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL);
SOAPMessage soapMsg = messageFactory.createMessage();
SOAPPart soapPart = soapMsg.getSOAPPart();
SOAPEnvelope soapEnv = soapPart.getEnvelope();
SOAPBody soapBody = soapEnv.getBody();
soapBody.addDocument(docBody);
// Invoke the webService.
System.out.println("Request SOAP Message:");
soapMsg.writeTo(System.out);
System.out.println("\n");
// Protocol 1.1=SOAP-ENV Content-Type:text/xml; charset=utf-8, 1.2=env Content-Type:application/soap+xml; charset=utf-8
SOAPEnvelope envelope = soapMsg.getSOAPPart().getEnvelope();
if (envelope.getElementQName().getNamespaceURI().equals("http://schemas.xmlsoap.org/soap/envelope/")) {
System.out.println("SOAP 1.1 NamespaceURI: http://schemas.xmlsoap.org/soap/envelope/");
serverDetails.put("Content-Type", "text/xml; charset=utf-8");
} else {
System.out.println("SOAP 1.2 NamespaceURI: http://www.w3.org/2003/05/soap-envelope");
serverDetails.put("Content-Type", "application/soap+xml; charset=utf-8");
}
getSOAPConnection(soapMsg); // Disadvantage 1:
getHttpURLConnection_Core(soapMsg);
}
private static URL getURL(String endPointUrl) throws MalformedURLException {
URL endpoint = new URL(null, endPointUrl, new URLStreamHandler() {
protected URLConnection openConnection(URL url) throws IOException {
URL clone = new URL(url.toString());
URLConnection connection = null;
if (PROXY_ADDRESS != null && PROXY_PORT != 0 ) { // https://stackoverflow.com/a/22533464/5081877
Socket socket = new Socket();
SocketAddress sockaddr = new InetSocketAddress(PROXY_ADDRESS, PROXY_PORT);
socket.connect(sockaddr, 10000);
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(socket.getInetAddress(), PROXY_PORT));
if (proxy.address().toString().equals("0.0.0.0/0.0.0.0:80") || proxy.address().toString() != null) {
System.out.println("Connection through proxy ...");
connection = clone.openConnection(proxy);
} else {
connection = clone.openConnection();
}
} else {
connection = clone.openConnection();
}
connection.setConnectTimeout(5 * 1000); // 5 sec
connection.setReadTimeout(5 * 1000); // 5 sec
return connection;
}
});
return endpoint;
}
public static String getSOAPXMLasString(SOAPMessage soapMsg) throws SOAPException, IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
soapMsg.writeTo(out);
// resp.writeTo(System.out);
String strMsg = new String(out.toByteArray());
System.out.println("Soap XML: "+ strMsg);
return strMsg;
}
public static SOAPMessage getSOAPMessagefromDataXML(String saopBodyXML) throws Exception {
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
dbFactory.setNamespaceAware(true);
dbFactory.setIgnoringComments(true);
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
InputSource ips = new org.xml.sax.InputSource(new StringReader(saopBodyXML));
Document docBody = dBuilder.parse(ips);
System.out.println("Data Document: "+docBody.getDocumentElement());
MessageFactory messageFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL);
SOAPMessage soapMsg = messageFactory.createMessage();
SOAPBody soapBody = soapMsg.getSOAPPart().getEnvelope().getBody();
soapBody.addDocument(docBody);
return soapMsg;
}
// SOPAConneciton and HTTPClien connection functions
}
did you see this?
SOAPMessage - SOAPConnection - gzip - how to
Also, if you use AXIS2, it has built-in features to enable compression of base64-encoded binary content using MTOM:
http://axis.apache.org/axis2/java/core/docs/mtom-guide.html
Just to complete that snippet - if you want to work with the decompressed SOAPMessage you need to load it into a new message.
SOAPMessage responseCompressed = connection.call(reqMessage, endpoint);
ByteArrayOutputStream out = new ByteArrayOutputStream();
responseCompressed.writeTo(out);
byte[] barr = out.toByteArray();
InputStream gzipStream = new GZIPInputStream(new ByteArrayInputStream(barr));
Here is the magic line
SOAPMessage response = factory.createMessage(responseCompressed.getMimeHeaders(), gzipStream);
Where factory is your MessageFactory.
Now response will function like it did without the gzip headers. You just drop it in.