sending a SOAP message via HTTP in java - java

I have the following code:
String xmldata = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>" +
"<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://www.w3.org/2003/05/soap-envelope\" " +
"xmlns:wsdl=\"http://schemas.xmlsoap.org/wsdl/\" " +
"xmlns:ns1=\"http://org.apache.axis2/xsd\" " +
"xmlns:ns=\"http://tfc\" " +
"xmlns:wsaw=\"http://www.w3.org/2006/05/addressing/wsdl\" " +
"xmlns:http=\"http://schemas.xmlsoap.org/wsdl/http/\" " +
"xmlns:xs=\"http://www.w3.org/2001/XMLSchema\"" +
"xmlns:mime=\"http://schemas.xmlsoap.org/wsdl/mime/\" " +
"xmlns:soap=\"http://schemas.xmlsoap.org/wsdl/soap/\" " +
"xmlns:soap12=\"http://schemas.xmlsoap.org/wsdl/soap12/\" " +
"xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" " +
"xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" > " +
"<SOAP-ENV:Body>" +
"<ns:CalFare xmlns:ns=\"http://tfc\">" +
"<ns:nonairport>1</ns:nonairport>" +
"<ns:distance>20</ns:distance>" +
"</ns:CalFare>" +
"</SOAP-ENV:Body>" +
"</SOAP-ENV:Envelope>";
//Create socket
String hostname = "128.196.239.112";
int port = 8080;
InetAddress addr = InetAddress.getByName(hostname);
Socket sock = new Socket(addr, port);
//Send header
String path = "/LocatorzTaxiFare/services/Calculator.CalculatorHttpSoap11Endpoint/";
BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(sock.getOutputStream(),"UTF-8"));
// You can use "UTF8" for compatibility with the Microsoft virtual machine.
wr.write("POST " + path + " HTTP/1.0\r\n");
wr.write("Host: 128.196.239.112\r\n");
wr.write("Content-Length: " + xmldata.length() + "\r\n");
wr.write("Content-Type: text/xml; charset=\"utf-8\"\r\n");
wr.write("\r\n");
//Send data
wr.write(xmldata);
wr.flush();
// Response
BufferedReader rd = new BufferedReader(new InputStreamReader(sock.getInputStream()));
String line;
while((line = rd.readLine()) != null)
System.out.println(line);
} catch (Exception e) {
e.printStackTrace();
}
Now it's giving me an internal server error with the following response:
<?xml version='1.0' encoding='utf-8'?><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"><soapenv:Header xmlns:wsa="http://www.w3.org/2005/08/addressing"><wsa:Action>http://www.w3.org/2005/08/addressing/soap/fault</wsa:Action></soapenv:Header><soapenv:Body><soapenv:Fault><faultcode></faultcode><faultstring>com.ctc.wstx.exc.WstxUnexpectedCharException: Unexpected character 'x' (code 120) excepted space, or '>' or "/>"
at [row,col {unknown-source}]: [1,390]</faultstring><detail /></soapenv:Fault></soapenv:Body></soapenv:Envelope>
Here's a link to the WSDL

At a glance, it looks like the XML that you're sending it is invalid. The XML processor found an 'x' when it was looking for a space, a '>' or a '/>'. So, fix your payload.
Yup...here it is:
"xmlns:xs=\"http://www.w3.org/2001/XMLSchema\"" +
"xmlns:mime=\"http://schemas.xmlsoap.org/wsdl/mime/\" " +
That first line is wrong, you need to add the trailing space (like in the second line).
Mind, it helps to read the error messages. This is exactly what it said was wrong. No real magic here.

Related

Constant 401 error with OAuth1 (MCM API)

I've been trying to establish a connection with an API for more than a week now, to no avail. (Magic Card Market's, authentification documentation here and there). I'm supposed to receive a XML file.
I have what MCM call a "widget" access to their API, meaning that I don't have nor need a oauth_token (it's supposed to be an empty string) for the authorization header, and that I'm not supposed to receive nor use an access token/access secret.
The only things I do have are a consumer key (they call it app token sometimes) and a consumer secret.
Here is how I build my Authorization header :
private static String buildOAuthAuthorization(String method, String request)
throws UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeyException {
String mkmAppToken = APICredentials.appToken;
String mkmAppSecret = APICredentials.appSecret;
String realm = "https://www.mkmapi.eu/ws/v1.1/games";
String oauthVersion = "1.0";
String oauthConsumerKey = mkmAppToken;
String oauthToken = "";
String oauthSignatureMethod = "HMAC-SHA1";
String oauthTimestamp = Long.toString(System.currentTimeMillis() / 1000);
String oauthNonce = Long.toString(System.currentTimeMillis());
String paramString = "oauth_consumer_key=" + oauthConsumerKey
+ "oauth_nonce=" + oauthNonce
+ "oauth_signature_method=" + oauthSignatureMethod
+ "oauth_timestamp=" + oauthTimestamp
+ "oauth_token=" + oauthToken
+ "oauth_version=" + oauthVersion;
String baseString = method + "&" + rawUrlEncode(realm) + "&" + rawUrlEncode(paramString);
String signingKey = rawUrlEncode(mkmAppSecret) + "&";
Mac mac = Mac.getInstance("HMAC-SHA1");
SecretKeySpec secret = new SecretKeySpec(signingKey.getBytes(), mac.getAlgorithm());
mac.init(secret);
byte[] digest = mac.doFinal(baseString.getBytes());
byte[] oauthSignature = Base64.encode(digest, Base64.URL_SAFE);
String authorizationProperty = "OAuth "
+ "realm=\"" + realm + "\", "
+ "oauth_version=\"" + oauthVersion + "\", "
+ "oauth_timestamp=\"" + oauthTimestamp + "\", "
+ "oauth_nonce=\"" + oauthNonce + "\", "
+ "oauth_consumer_key=\"" + oauthConsumerKey + "\", "
+ "oauth_token=\""+ oauthToken + "\", "
+ "oauth_signature_method=\"" + oauthSignatureMethod + "\", "
+ "oauth_signature=\"" + oauthSignature + "\"";
System.out.println(authorizationProperty);
return authorizationProperty;
}
The actual request is in an AsyncTask :
public static class oAuthRequest extends AsyncTask<String, Integer, StringReader> {
private int lastCode;
#Override
protected StringReader doInBackground(String... requestURLs) {
String method = requestURLs[0];
String url = requestURLs[1];
StringReader result = null;
try {
String authProperty = buildOAuthAuthorization(method, url);
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
connection.addRequestProperty("Authorization:", authProperty);
lastCode = connection.getResponseCode();
System.out.println("RESPONSE CODE 1 " + lastCode);
// Get content
BufferedReader rd = new BufferedReader(new InputStreamReader(lastCode == 200 ? connection.getInputStream() : connection.getErrorStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = rd.readLine()) != null) {
sb.append(line);
}
rd.close();
result = new StringReader(sb.toString());
} catch (NoSuchAlgorithmException | InvalidKeyException | IOException e) {
e.printStackTrace();
}
return result;
}
}
It seems like no matter what I change, I'm always getting a 401.
Things I've tried :
oauthSignature as a String using Base64.encodeToString()
Nonce generation using SecureRandom
With and without the empty oauthToken
Another timestamp generation method (can't remember what though)
signing key with and without app token (theorically I need only the consumer secret, but you never know)
Using HttpsURLConnection instead of HttpURLConnection (the URI start in https, so I thought, hey. But no)
At least 2-3 other different implementations (one who was basically a copy/paste of the Java example in the documentation of course -- it still kind of is one now)
(Probably a lot of things I can't even remember)
At this point I'm wondering if maybe the issue comes from my keys, as I've tried to use the Postman app to test requests with the same results.

getting a invalid_request_body error when i try to void a document

When trying to void a in-progress document, I received the invalid_request_body error(The request body is missing or improperly formatted. Data at the root level is invalid). Is there something missing on the request body ?
url = baseURL + "/envelopes/" + envelopeId;
body = "";
// re-use connection object for second request...
conn = InitializeRequest(url, "PUT", body, authenticationHeader);
String requestBody = "\r\n\r\n--BOUNDARY\r\n" +
"Accept: application/xml" +
"Content-Type: application/xml\r\n" +
"\r\n" +
body + "\r\n\r\n--BOUNDARY\r\n" +
"status: voided\r\n" +
"voidedReason: Time-out\r\n" +
"\r\n";
String reqBody2 = "\r\n" + "--BOUNDARY--\r\n\r\n";
DataOutputStream dos= new DataOutputStream( conn.getOutputStream() );
dos.writeBytes(requestBody.toString());
//dos.write(bytes);
dos.writeBytes(reqBody2.toString());
dos.flush();
dos.close();
System.out.println("STEP 2: Retrieving envelope information for envelope " + envelopeId + ".\n");
status = conn.getResponseCode(); // triggers the request
if( status != 200 ) { // 200 = OK
System.out.println(conn);
System.out.println(status);
errorParse(conn, status);
throw new RuntimeException();
}
// display results
response = getResponseBody(conn);
Following up with your comments for the benefit of the community...
This is the request body that worked for you in the end:
request body## String requestBody = "<envelope>" + "<status>voided</status>" + "<voidedReason>user aborted</voidedReason>" + "</envelope>"

java.lang.NumberFormatException: null in Integer.parseInt

Okay, the following are 2 classes that I am using in creating a simple TFTP (Trivial File Transfer Protocol) program. I am running a server instance and a client instance of this program. What I am trying to accomplish is this:
The client connects to the server and sends a message of a specific file that it wants. The server locates the file and sends a response (either a 1 or 0... 1 meaning the file is there, and 0 meaning that it is not). Then the server will send the content of the file to the client application. The files I am trying to send are just simple text files.
Right now, I am able to receive the name of the text file that the client wants, but then when I go to send back the response, I am not getting anything returned. Also below are the methods that the server and the client both run.
This is the server instance
SwingUtilities.invokeLater(new Runnable(){
public void run(){
String fileRequest = UDPReceiver(SERVER_PORT_NUMBER);
outputArea.append("\n" + "File Requested: " + fileRequest + "\n");
outputArea.append("Determining if file exists...\n");
String checkFile = SHARED_DIR + "\\" + fileRequest;
outputArea.append("Checking location: " + checkFile + "\n");
boolean check = fileCheck(checkFile);
if(check == true){
outputArea.append("File location verified..." + "\n");
outputArea.append("Initiating transfer...." + "\n\n");
UDPSender(CLIENT_HOSTNAME, CLIENT_PORT_NUMBER, "1");
}
else{
outputArea.append("File does not exist..." + "\n");
outputArea.append("Exiting run..." + "\n");
}
}
});
The client instance.
SwingUtilities.invokeLater(new Runnable(){
public void run(){
UDPSender(SERVER_HOSTNAME, SERVER_PORT_NUMBER, FILE_REQUEST);
String message = UDPReceiver(CLIENT_PORT_NUMBER);
outputArea.append("\n\n" + message + "\n");
if(message == "1"){
// File exists
outputArea.append("\n");
outputArea.append("File verified..." + "\n");
outputArea.append("Transfer initiated..." + "\n");
}
else{
// File doesn't exist
outputArea.append("\n");
outputArea.append("File does not exist..." + "\n");
outputArea.append("Terminating connection...");
}
}
});
Here are the Sender and Receiver methods.
private void UDPSender(String hostname, String port, String message){
DatagramSocket socket = null;
try{
// Create a datagram socket, look for the first available port
socket = new DatagramSocket();
outputArea.append("Using local port: " + socket.getLocalPort() + "\n");
ByteArrayOutputStream bOut = new ByteArrayOutputStream();
PrintStream pOut = new PrintStream(bOut);
pOut.print(message);
// Convert printstream to byte array
byte[] bArray = bOut.toByteArray();
// Create a DatagramPacket, containing a maximum buffer of 256 bytes
DatagramPacket packet = new DatagramPacket(bArray, bArray.length);
outputArea.append("Looking for hostname " + hostname + "\n");
// Get the InetAddress object
InetAddress remote_addr = InetAddress.getByName(hostname);
// Check its IP Number
outputArea.append("Hostname has IP Address = " + remote_addr.getHostAddress() + "\n");
// Configure the DatagramPacket
packet.setAddress(remote_addr);
packet.setPort(Integer.parseInt(port));
// Send the packet
socket.send(packet);
outputArea.append("Packet sent at: " + new Date() + "\n");
// Display packet information
outputArea.append("Sent by: " + remote_addr.getHostAddress() + "\n");
outputArea.append("Sent from: " + packet.getPort() + "\n");
socket.close();
}
catch(UnknownHostException ue){
outputArea.append("Unknown host: " + hostname + "\n");
outputArea.append("Unknown host: " + ue + "\n");
}
catch(IOException e){
outputArea.append("Error: " + e + "\n");
}
}
private String UDPReceiver(String portNum){
String message = "";
DatagramSocket socket = null;
try{
// Create a DatagramSocket
socket = new DatagramSocket(Integer.parseInt(portNum));
outputArea.append("Listening on local port " + socket.getLocalPort() + "\n");
// Create a DatagramPacket, containing a maximum buffer of 256 bytes
DatagramPacket packet = new DatagramPacket(new byte[256], 256);
// Receive a packet - remember by default this is a blocking operation
socket.receive(packet);
outputArea.append("Packet received at " + new Date() + "\n");
// Display packet information
InetAddress remote_addr = packet.getAddress();
outputArea.append("Sender: " + remote_addr.getHostAddress() + "\n");
outputArea.append("From Port: " + packet.getPort() + "\n");
CLIENT_HOSTNAME = remote_addr.getHostAddress();
//CLIENT_PORT_NUMBER = Integer.toString(packet.getPort());
// Display packet contents, by reading from byte array
ByteArrayInputStream bin = new ByteArrayInputStream(packet.getData());
// Display only up to the length of the original UDP packet
for(int i = 0; i < packet.getLength(); i++){
int data = bin.read();
if(data == -1){
break;
}
else{
message = message + (char)data;
//outputArea.append(Character.toString((char)data));
}
}
socket.close();
return message;
}
catch(IOException e){
outputArea.append("Error: " + e + "\n");
message = "Error: " + e;
return message;
}
}
Any help that you folks can offer would be greatly appreciated. The main thing I am trying to figure out is how to be able to get the server and client to be able to send messages back and forth. Thanks in advance guys.
EDIT:
I am also getting an error now in Netbeans when I run this project. I think it has something to do with this line of code in the UDPReceiver method:
socket = new DatagramSocket(Integer.parseInt(portNum));
But I can't figure out what is wrong with that.
Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: null
at java.lang.Integer.parseInt(Integer.java:454)
at java.lang.Integer.parseInt(Integer.java:527)
at tftp_gui.main.UDPReceiver(main.java:508)
at tftp_gui.main.access$800(main.java:20)
at tftp_gui.main$10.run(main.java:374)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:251)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:721)
at java.awt.EventQueue.access$200(EventQueue.java:103)
at java.awt.EventQueue$3.run(EventQueue.java:682)
at java.awt.EventQueue$3.run(EventQueue.java:680)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:691)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:244)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:163)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:151)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:147)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:139)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:97)
you approach is wrong, as it is requires opened client port, anyway your particular problem is because you're not sending back result when file is not found:
check:
if(check == true){
outputArea.append("File location verified..." + "\n");
outputArea.append("Initiating transfer...." + "\n\n");
UDPSender(CLIENT_HOSTNAME, CLIENT_PORT_NUMBER, "1");
}
else {
outputArea.append("File does not exist..." + "\n");
outputArea.append("Exiting run..." + "\n");
UDPSender(CLIENT_HOSTNAME, CLIENT_PORT_NUMBER, "0"); // here you should send 0
}
also, you have small problem here: if(message == "1") it should look like if ("1".equals(message))
Your error is self explainable - you're haven't declared proper CLIENT_PORT_NUMBER or SERVER_PORT_NUMBER, here is what I've used for testing:
private final static String SERVER_PORT_NUMBER = "1234";
private static String CLIENT_HOSTNAME;
private static final String CLIENT_PORT_NUMBER = "2345";
private static final String FILE_REQUEST = "a.txt";
private static final String SHARED_DIR = "d:/";
private static final String SERVER_HOSTNAME = "localhost";

Sending post attributes and xml data with a post request?

New to java, GWT and interacting with APIs. I have what I hope is a simple question.
I have successfully interacted with a REST API using the following curl command:
curl -d "OPERATION_NAME=ADD_REQUEST&TECHNICIAN_KEY=xxxxxxxxxxx&INPUT_DATA=<?xml version=%221.0%22 encoding=%22utf-8%22?><Operation><Details><requester>Me</requester><subject>Test</subject><description>Testing curl input</description></Details></Operation>" http://xx.xx.xx.xx/sdpapi/request/
Now, from a tutorial, I have the following code that I am hoping will post a request to the remote server just like the curl command above.
What I am trying to figure out (with no love from google) is how I pass the OPERATION_NAME, TECHNICIAN_KEY and INPUT_DATA parameters in when I am sending the URL. Any suggestions, tutorials, etc. will be appreciated.
The following is from my server side implementation interface:
#Override
public String postToRemoteServer(String serviceUrl)
throws HelpDeskTestException {
try {
//dividing url into host: http://some.server
//path: a/path/in/it
//and parameters: this=that&those=others
int hostStart= serviceUrl.indexOf("//");
int pathStart= serviceUrl.substring(hostStart + 2).indexOf("/");
int parameterStart= serviceUrl.substring(hostStart + 2 + pathStart).indexOf("?");
final String serverHost= serviceUrl.substring(0, hostStart + pathStart + 2);
final String serverPath= serviceUrl.substring(hostStart + 3,
hostStart + pathStart + 2 + parameterStart);
final String serverParameters= serviceUrl.substring(hostStart + pathStart + 3 + parameterStart);
final URL url = new URL(serverHost);
final URLConnection connection= url.openConnection();
connection.setDoOutput(true);
final OutputStreamWriter out= new OutputStreamWriter(connection.getOutputStream());
final BufferedReader in= new BufferedReader(new InputStreamReader(
connection.getInputStream()));
out.write("POST " + serverPath + "\r\n");
out.write("Host: " + serverHost + "\r\n");
out.write("Accept-Encoding: identity\r\n");
out.write("Connection: close\r\n");
out.write("Content-Type: application/x-www-form-urlencoded\r\n");
out.write("Content-Length: " + serverParameters.length() + "\r\n\r\n" +
serverParameters + "\r\n");
String result = "";
String inputLine;
while ((inputLine=in.readLine()) != null) {
result+= inputLine;
}
in.close();
out.close();
return result;
} catch (final Exception e) {
throw new HelpDeskTestException();
}
Consider using this library: Apache HttpClient. Here is an example of making a POST request with it.

How to access servlet and download attachment?

I have the following code snippet that tries to make an HTTP call to my servlet:
try {
// Construct data
String data = URLEncoder.encode("rpt_type", "UTF-8") + "=" + URLEncoder.encode(reportType, "UTF-8");
data += "&" + URLEncoder.encode("rpt_project", "UTF-8") + "=" + URLEncoder.encode(reportProject, "UTF-8");
data += "&" + URLEncoder.encode("rpt_mrv_creator", "UTF-8") + "=" + URLEncoder.encode(reportMrvCreator, "UTF-8");
data += "&" + URLEncoder.encode("rpt_gi_recipient", "UTF-8") + "=" + URLEncoder.encode(reportGiRecipient, "UTF-8");
data += "&" + URLEncoder.encode("rpt_plant", "UTF-8") + "=" + URLEncoder.encode(reportPlant, "UTF-8");
data += "&" + URLEncoder.encode("rpt_sloc", "UTF-8") + "=" + URLEncoder.encode(reportStorageLoc, "UTF-8");
data += "&" + URLEncoder.encode("rpt_gi_no", "UTF-8") + "=" + URLEncoder.encode(reportGiNo, "UTF-8");
data += "&" + URLEncoder.encode("date_sap_gi_fr", "UTF-8") + "=" + URLEncoder.encode(reportDateGiFrom, "UTF-8");
data += "&" + URLEncoder.encode("date_sap_gi_to", "UTF-8") + "=" + URLEncoder.encode(reportDateGiTo, "UTF-8");
data += "&" + URLEncoder.encode("rpt_partno", "UTF-8") + "=" + URLEncoder.encode(reportPartNo, "UTF-8");
data += "&" + URLEncoder.encode("rpt_so_no", "UTF-8") + "=" + URLEncoder.encode(reportSvcOrderNo, "UTF-8");
data += "&" + URLEncoder.encode("date_scan_fr", "UTF-8") + "=" + URLEncoder.encode(reportDateScanFrom, "UTF-8");
data += "&" + URLEncoder.encode("date_scan_to", "UTF-8") + "=" + URLEncoder.encode(reportDateScanTo, "UTF-8");
System.out.println("[data]\n" + data);
// Send data
String urlString = "http://localhost:8080/aerobook/GIStatusReportDownload?" + data;
System.out.println("[url] " + urlString);
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
//conn.setDoOutput(true);
//OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
//wr.write(data);
//wr.flush();
// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
System.out.println(line);
}
//wr.close();
rd.close();
} catch (Exception e) {
}
My debug output:
[data]
rpt_type=d&rpt_project=aaa&rpt_mrv_creator=bbb&rpt_gi_recipient=ccc&rpt_plant=ddd&rpt_sloc=eee&rpt_gi_no=fff&date_sap_gi_fr=02%2F05%2F2012&date_sap_gi_to=03%2F05%2F2012&rpt_partno=ggg&rpt_so_no=hhh&date_scan_fr=26%2F05%2F2012&date_scan_to=31%2F05%2F2012
[url] http://localhost:8080/aerobook/GIStatusReportDownload?rpt_type=d&rpt_project=aaa&rpt_mrv_creator=bbb&rpt_gi_recipient=ccc&rpt_plant=ddd&rpt_sloc=eee&rpt_gi_no=fff&date_sap_gi_fr=02%2F05%2F2012&date_sap_gi_to=03%2F05%2F2012&rpt_partno=ggg&rpt_so_no=hhh&date_scan_fr=26%2F05%2F2012&date_scan_to=31%2F05%2F2012
On my servlet (in a separate file from the code above), I generate an Excel file for download:
res.setContentType(sContentType);
res.setHeader("Content-Disposition", "attachment;filename=\"" + sExcelFileName + "\"");
OutputStream oOutStrm = res.getOutputStream();
wbBook.write(oOutStrm);
oOutStrm.close();
My issue here is that from the URL generated by my code (as shown in the debug output above), I can access my servlet and I manage to get the Save-As dialog.
I'd like to get the contents of the file generated for use within my code. Is there any way I can get the attachment from my code, in byte stream or any other format?
Edit #3: Cleaned up the top
When you enter the URI into the browser, you are doing a GET request. Your client Java code however produces a POST request, and sends the parameters in the body, not the URI.
You may want to look at an HTTP trace and compare.
I want to get the contents of the excel file on my code, but so far it's not working.
I find no errors in the code.
I believe you want to convert content from input stream to an HSSFWorkbook object.
Following code snippet will help you on it.
java.net.URLConnection conn = url.openConnection();
java.io.InputStream is = conn.getInputStream();
org.apache.poi.hssf.usermodel.HSSFWorkbook workBook = new org.apache.poi.hssf.usermodel.HSSFWorkbook( is );
System.out.println( "Number of Sheets: " + workBook.getNumberOfSheets() );
org.apache.poi.hssf.usermodel.HSSFSheet sheet = workBook.getSheetAt( 0 );
System.out.println( "Sheet Name: " + sheet.getSheetName() );
// rest of your code to handle the captured workBook
// cheers
Check wbBook.write(oOutStrm); whether anything has been written into outputStream, also you need call oOutStrm.flash() before close it.
I doubt that the problem lies at OutputStream oOutStrm = res.getOutputStream();.
I bet res is HttpServletResponse and it returns a ServletOutputStream suitable for writing binary data in the response. The servlet container does not encode the binary data
Check API
So, You might not be getting anything except fileName.
In Servlet Try
FileOutputStream stream = new FileOutputStream("c:/excel/Book1.xls");
workBook.write(stream);

Categories