错误 - 代码在NetBeans中有效,但在.jar命令行中无效

时间:2016-12-27 11:10:56

标签: java soap netbeans jar

我有一个相当奇怪的问题。以下代码已完成。我的项目只有这个课程。在netbeans中,我可以正常运行它,没有任何问题。但是,当我通过java -jar "C:\Users\lucas\Documents\NetBeansProjects\WS_Apisul\dist\WS.jar"运行时,代码无法按照您想要的方式运行,特别是当您输入soapResponse = soapConnection.call(msg,url)时。

返回的错误如下:

dez 27, 2016 8:39:25 AM com.sun.xml.internal.messaging.saaj.client.p2p.HttpSOAPConnection post
GRAVE: SAAJ0008: Resposta Incorreta; Bad Request
Exception in thread "main" com.sun.xml.internal.messaging.saaj.SOAPExceptionImpl: com.sun.xml.internal.messaging.saaj.SOAPExceptionImpl: Bad response: (400Bad Request
        at com.sun.xml.internal.messaging.saaj.client.p2p.HttpSOAPConnection.call(Unknown Source)
        at ws.WS.main(WS.java:86)
Caused by: com.sun.xml.internal.messaging.saaj.SOAPExceptionImpl: Bad response: (400Bad Request
        at com.sun.xml.internal.messaging.saaj.client.p2p.HttpSOAPConnection.post(Unknown Source)
        ... 2 more

CAUSE:

com.sun.xml.internal.messaging.saaj.SOAPExceptionImpl: Bad response: (400Bad Request
        at com.sun.xml.internal.messaging.saaj.client.p2p.HttpSOAPConnection.post(Unknown Source)
        at com.sun.xml.internal.messaging.saaj.client.p2p.HttpSOAPConnection.call(Unknown Source)
        at ws.WS.main(WS.java:86)

代码

package ws;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileFilter;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.StringWriter;
import java.nio.file.Files;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.soap.MessageFactory;
import javax.xml.soap.MimeHeaders;
import javax.xml.soap.SOAPConnection;
import javax.xml.soap.SOAPConnectionFactory;
import javax.xml.soap.SOAPException;
import javax.xml.soap.SOAPMessage;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;


public class WS {

    /**
     * @param args the command line arguments
     */
    static int tipo=0;
    static String diretorioIn = "C:\\res\\in";
    static String diretorioInTMP = "C:\\res\\in\\tmp";
    static String diretorioOut = "C:\\res\\out\\";
    static String nomegerado ="";
    static String deleta ="";
    static String deleta2 ="";
    static File deletar = null;
    static int control = 0;
    public static void main(String[] args) throws SOAPException, FileNotFoundException, InterruptedException {

        String requestSoap;

        requestSoap = lerPasta();
        System.out.println(requestSoap);
        if(tipo == 1){ // CAN
            System.out.println("Iniciando cancelamento");
            SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
            SOAPConnection soapConnection = soapConnectionFactory.createConnection();
            String url = "MINHAURL.svc?wsdl";
            MimeHeaders headers = new MimeHeaders();
            headers.addHeader("Content-Type", "text/xml");


            headers.addHeader("SOAPAction", "http://tempuri.org/Cancela");
            MessageFactory messageFactory = MessageFactory.newInstance();

            SOAPMessage msg = null;
            try {
                msg = messageFactory.createMessage(headers, (new ByteArrayInputStream(requestSoap.getBytes())));
                System.out.println();
            } catch (IOException ex) {
                Logger.getLogger(WS.class.getName()).log(Level.SEVERE, null, ex);
            }

            SOAPMessage soapResponse = soapConnection.call(msg, url);


            Document xmlRespostaARequisicao=soapResponse.getSOAPBody().getOwnerDocument();
            System.out.println(passarXMLParaString(xmlRespostaARequisicao,4));
            gerarArquivoRetorno(passarXMLParaString(xmlRespostaARequisicao,4), "CAN");

        }
        else if(tipo == 2){ // INS

            System.out.println("Iniciando inserção");
            SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
            SOAPConnection soapConnection = soapConnectionFactory.createConnection();
            String url = "MINHAURL.svc?wsdl";
            MimeHeaders headers = new MimeHeaders();
            headers.addHeader("Content-Type", "text/xml");

            headers.addHeader("SOAPAction", "http://tempuri.org/Insere");

            MessageFactory messageFactory = MessageFactory.newInstance();

            SOAPMessage msg = null;
            try {
                msg = messageFactory.createMessage(headers, (new ByteArrayInputStream(requestSoap.getBytes())));
            } catch (IOException ex) {
                Logger.getLogger(WS.class.getName()).log(Level.SEVERE, null, ex);
            }

            SOAPMessage soapResponse = soapConnection.call(msg, url);
            Document xmlRespostaARequisicao=soapResponse.getSOAPBody().getOwnerDocument();
            System.out.println(passarXMLParaString(xmlRespostaARequisicao,4));
            gerarArquivoRetorno(passarXMLParaString(xmlRespostaARequisicao,4), "INS");

        }
        else{
             System.out.println("FORMATO INVÁLIDO DE NOME DE ARQUIVO");             
        }



    }
    public static String passarXMLParaString(Document xml, int espacosIdentacao){
        try {
            //set up a transformer
            TransformerFactory transfac = TransformerFactory.newInstance();
            transfac.setAttribute("indent-number", new Integer(espacosIdentacao));
            Transformer trans = transfac.newTransformer();
            trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
            trans.setOutputProperty(OutputKeys.INDENT, "yes");

            //create string from xml tree
            StringWriter sw = new StringWriter();
            StreamResult result = new StreamResult(sw);
            DOMSource source = new DOMSource(xml);
            trans.transform(source, result);
            String xmlString = sw.toString();
            return xmlString;
        }
        catch (TransformerException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            System.exit(0);
        }
        return null;
    }
    public static String gerarArquivoRetorno(String string, String metodo){
         File arquivo = new File(diretorioOut+metodo+nomegerado);
            try( FileWriter fw = new FileWriter(arquivo) ){
                fw.write(string);         
                    fw.flush();
                    File del = new File("C:\\res\\in\\del\\");                  
                    Files.delete(deletar.toPath());

                }catch(IOException ex){
                  ex.printStackTrace();
                }                
        return null;    
    }
    public static void verificaTipoXML(String nome){        
        if(nome.startsWith("CAN", diretorioIn.length()+1)){
            tipo = 1;            
        }
        else if(nome.startsWith("INS", diretorioIn.length()+1)){
            tipo = 2;
        }
        else{
            tipo = 0;
        }

    }
    public static String lerPasta() throws FileNotFoundException{
        FileFilter filter = new FileFilter() {
        public boolean accept(File file) {
            return file.getName().endsWith(".xml");
            }
        };
        File dir = new File(diretorioIn);
        String texto = null;
        File[] files = dir.listFiles(filter);
        for(int i = 0; i < files.length ; i++){
            Scanner s = new Scanner(new File(files[i].toString()), "UTF-8");
            texto = s.useDelimiter("\\A").next();     
            verificaTipoXML(files[i].toString());
            System.out.println("lerPasta():" + files[i].toString());
            System.out.println("verificaTipoXML():" + files[i].toString().substring(diretorioIn.length()+1));
            deleta = files[i].toString();
            deleta2 = files[i].toString().substring(diretorioIn.length()+1);
            deletar = files[i];
            System.out.println(deleta2);
            nomegerado = files[i].toString().substring(diretorioIn.length()+4);
            System.out.println("GLOBAL:nomegerado:" + nomegerado);
            s.close();
         }
        return texto;
    }


}

1 个答案:

答案 0 :(得分:0)

错误发生在代码的开头。

RequestSoap = lerPasta();

您的错误表明发送的请求不正确,确实如此。当文件夹为空时发生错误,即它向服务器发送null,并显示错误。

你可以解决这个问题

   RequestSoap = lerPasta();
    If (requestSoap == null) {
        RequestSoap = lerPasta();
    }
    Else {
        // Your code
    }