簡體   English   中英

如何在 Java 中發送原始 SOAP 請求?

[英]How to send raw SOAP request in Java?

我需要向服務器發送原始 SOAP 請求。 我的請求看起來像

POST http://10.76.243.43:8080/registry/services/xds-iti18 HTTP/1.1
Accept-Encoding: gzip,deflate
Content-Type: application/soap+xml;charset=UTF-8
Content-Length: 6383
Host: 10.76.243.43:8080
Connection: Keep-Alive
User-Agent: Apache-HttpClient/4.1.1 (java 1.5)

<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:urn="urn:oasis:names:tc:ebxml-regrep:xsd:query:3.0" xmlns:urn1="urn:oasis:names:tc:ebxml-regrep:xsd:rs:3.0" xmlns:urn2="urn:oasis:names:tc:ebxml-regrep:xsd:rim:3.0">
   <soap:Header/>
   <soap:Body>
      <urn:AdhocQueryRequest id="?" comment="?" federated="false" federation="?" startIndex="0" maxResults="-1">
         <!--Optional:-->
         <urn1:RequestSlotList>
            <!--Zero or more repetitions:-->
            <urn2:Slot name="?" slotType="?">
               <urn2:ValueList>
                  <urn2:Value>?</urn2:Value>
               </urn2:ValueList>
            </urn2:Slot>
         </urn1:RequestSlotList>
         <urn:ResponseOption returnType="RegistryObject" returnComposedObjects="false"/>
         <urn2:AdhocQuery id="?" home="?" lid="?" objectType="?" status="?">
            <!--Zero or more repetitions:-->
            <urn2:Slot name="?" slotType="?">
               <urn2:ValueList>
                  <urn2:Value>?</urn2:Value>
               </urn2:ValueList>
            </urn2:Slot>
            <!--Optional:-->
            <urn2:Name>
               <urn2:LocalizedString xml:lang="en-US" charset="UTF-8" value="?"/>
            </urn2:Name>
            <!--Optional:-->
            <urn2:Description>
               <urn2:LocalizedString xml:lang="en-US" charset="UTF-8" value="?"/>
            </urn2:Description>
            <!--Optional:-->
            <urn2:VersionInfo versionName="1.1" comment="?"/>
            <!--Zero or more repetitions:-->
            <urn2:Classification id="?" home="?" lid="?" objectType="?" status="?" classificationScheme="?" classifiedObject="?" classificationNode="?" nodeRepresentation="?">
               <!--Zero or more repetitions:-->
               <urn2:Slot name="?" slotType="?">
                  <urn2:ValueList>
                     <urn2:Value>?</urn2:Value>
                  </urn2:ValueList>
               </urn2:Slot>
               <!--Optional:-->
               <urn2:Name>
                  <urn2:LocalizedString xml:lang="en-US" charset="UTF-8" value="?"/>
               </urn2:Name>
               <!--Optional:-->
               <urn2:Description>
                  <urn2:LocalizedString xml:lang="en-US" charset="UTF-8" value="?"/>
               </urn2:Description>
               <!--Optional:-->
               <urn2:VersionInfo versionName="1.1" comment="?"/>
               <!--Zero or more repetitions:-->
               <urn2:Classification/>
               <!--Zero or more repetitions:-->
               <urn2:ExternalIdentifier id="?" home="?" lid="?" objectType="?" status="?" registryObject="?" identificationScheme="?" value="?">
                  <!--Zero or more repetitions:-->
                  <urn2:Slot name="?" slotType="?">
                     <urn2:ValueList>
                        <urn2:Value>?</urn2:Value>
                     </urn2:ValueList>
                  </urn2:Slot>
                  <!--Optional:-->
                  <urn2:Name>
                     <urn2:LocalizedString xml:lang="en-US" charset="UTF-8" value="?"/>
                  </urn2:Name>
                  <!--Optional:-->
                  <urn2:Description>
                     <urn2:LocalizedString xml:lang="en-US" charset="UTF-8" value="?"/>
                  </urn2:Description>
                  <!--Optional:-->
                  <urn2:VersionInfo versionName="1.1" comment="?"/>
                  <!--Zero or more repetitions:-->
                  <urn2:Classification/>
                  <!--Zero or more repetitions:-->
                  <urn2:ExternalIdentifier/>
               </urn2:ExternalIdentifier>
            </urn2:Classification>
            <!--Zero or more repetitions:-->
            <urn2:ExternalIdentifier id="?" home="?" lid="?" objectType="?" status="?" registryObject="?" identificationScheme="?" value="?">
               <!--Zero or more repetitions:-->
               <urn2:Slot name="?" slotType="?">
                  <urn2:ValueList>
                     <urn2:Value>?</urn2:Value>
                  </urn2:ValueList>
               </urn2:Slot>
               <!--Optional:-->
               <urn2:Name>
                  <urn2:LocalizedString xml:lang="en-US" charset="UTF-8" value="?"/>
               </urn2:Name>
               <!--Optional:-->
               <urn2:Description>
                  <urn2:LocalizedString xml:lang="en-US" charset="UTF-8" value="?"/>
               </urn2:Description>
               <!--Optional:-->
               <urn2:VersionInfo versionName="1.1" comment="?"/>
               <!--Zero or more repetitions:-->
               <urn2:Classification id="?" home="?" lid="?" objectType="?" status="?" classificationScheme="?" classifiedObject="?" classificationNode="?" nodeRepresentation="?">
                  <!--Zero or more repetitions:-->
                  <urn2:Slot name="?" slotType="?">
                     <urn2:ValueList>
                        <urn2:Value>?</urn2:Value>
                     </urn2:ValueList>
                  </urn2:Slot>
                  <!--Optional:-->
                  <urn2:Name>
                     <urn2:LocalizedString xml:lang="en-US" charset="UTF-8" value="?"/>
                  </urn2:Name>
                  <!--Optional:-->
                  <urn2:Description>
                     <urn2:LocalizedString xml:lang="en-US" charset="UTF-8" value="?"/>
                  </urn2:Description>
                  <!--Optional:-->
                  <urn2:VersionInfo versionName="1.1" comment="?"/>
                  <!--Zero or more repetitions:-->
                  <urn2:Classification/>
                  <!--Zero or more repetitions:-->
                  <urn2:ExternalIdentifier/>
               </urn2:Classification>
               <!--Zero or more repetitions:-->
               <urn2:ExternalIdentifier/>
            </urn2:ExternalIdentifier>
            <!--Optional:-->
            <urn2:QueryExpression queryLanguage="?">
               e
               <!--You may enter ANY elements at this point-->
               gero
            </urn2:QueryExpression>
         </urn2:AdhocQuery>
      </urn:AdhocQueryRequest>
   </soap:Body>
</soap:Envelope>

它是由 SOAP UI(使用 Web 服務的 wsdl)生成的標准原始請求,所以如果我將它發送到那里,我會得到 HTTP 代碼 200 和一些正常響應。 我想使用 Java 發送它,所以我執行以下操作

byte[] encoded = Files.readAllBytes(Paths.get("C:\\Users\\timofb\\Documents\\testtest.txt"));//file with my raw request
String soapXml = new String(encoded, StandardCharsets.UTF_8);
Socket socket = new Socket("10.76.243.43", 8080);
BufferedWriter out = new BufferedWriter(
            new OutputStreamWriter(socket.getOutputStream(), "UTF8"));
BufferedReader in = new BufferedReader(
            new InputStreamReader(socket.getInputStream()));
out.write(soapXml);
out.flush();
System.out.println("\n * Response");    
String line;
while ((line = in.readLine()) != null) {
     System.out.println(line);
}
in.close();

我收到 HTTP 狀態 500 和處理時發生錯誤的 SOAP 消息。 謝謝。

你可以這樣嘗試:你需要用你的替換xmldata:

   try {
        String xmldata = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><soapenv:Envelopey> your reuest</soapenv:Envelope>";
        String hostname = "10.76.243.43";
        int port = 8080;
        InetAddress addr = InetAddress.getByName(hostname);
        Socket sock = new Socket(addr, port);

        //Send header
        String path = "registry/services/xds-iti18";
        BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(sock.getOutputStream(), "UTF-8"));
        wr.write("POST "+path + " HTTP/1.1\r\n");
        wr.write("Host: "+hostname+":"+port+"\r\n");
        wr.write("Content-Length: "+ xmldata.length() + "\r\n");
        wr.write("Content-Type: application/soap+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("Response:"+line);
        }
} catch (Exception e) {
   e.printStackTrace();
}

我找到了答案。 這段代碼對我有用

    byte[] encoded = Files.readAllBytes(Paths.get("C:\\Users\\timofb\\Documents\\test.txt"));
    String soapXml = new String(encoded, StandardCharsets.UTF_8);
    SOAPConnectionFactory soapConnectionFactory =
            SOAPConnectionFactory.newInstance();
    java.net.URL endpoint = new URL("http://" + ip + "/cs-repository/services/xds-iti41");
    SOAPConnection connection = soapConnectionFactory.createConnection();
    MessageFactory factory = MessageFactory.newInstance();
    SOAPMessage message = factory.createMessage(new MimeHeaders(), new ByteArrayInputStream(encoded));
    AttachmentPart attachment = message.createAttachmentPart();
    attachment.setContent("sm_content", "text/plain");
    attachment.setContentId("1.9f910338bf0cac0e783bfdec7e53be9237684caa8f8f4e6d@apache.org");
    message.addAttachmentPart(attachment);
    SOAPMessage response = connection.call(message, endpoint);
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    response.writeTo(out);
    String strMsg = new String(out.toByteArray());
    return strMsg;

我知道這有點晚了,但 Unirest 救了我很多。

您應該簡單地嘗試以下操作:

        Unirest.setTimeouts(0, 0);
        HttpResponse<String> response = Unirest.post("YOUR URL OPERATION")
          .header("Content-Type", "application/soap+xml")
          .body("YOUR RAW FILE")
          .asString();

您可以使用 java HttpURLConnection 代替套接字,在這里您必須正確設置 SOAPAction 標頭屬性,以防它是“AdhocQueryRequest”,或者您可以從您的 wsdl 進行交叉檢查,以下是未經測試的暫定代碼。

    URL url = new URL(SOAPUrl);
    URLConnection connection = url.openConnection();
    HttpURLConnection httpConn = (HttpURLConnection) connection;
    FileInputStream fin = new FileInputStream(xmlFile2Send);

    ByteArrayOutputStream bout = new ByteArrayOutputStream();

    // Copy the SOAP file to the open connection.
    copy(fin,bout);
    fin.close();

    byte[] b = bout.toByteArray();

    // Set the appropriate HTTP parameters.
    httpConn.setRequestProperty( "Content-Length",
                                 String.valueOf( b.length ) );
    httpConn.setRequestProperty("Content-Type","text/xml; charset=utf-8");
      httpConn.setRequestProperty("SOAPAction",SOAPAction);
    httpConn.setRequestMethod( "POST" );
    httpConn.setDoOutput(true);
    httpConn.setDoInput(true);

    // Everything's set up; send the XML that was read in to b.
    OutputStream out = httpConn.getOutputStream();
    out.write( b );    
    out.close();

    // Read the response and write it to standard out.

    InputStreamReader isr =
        new InputStreamReader(httpConn.getInputStream());
    BufferedReader in = new BufferedReader(isr);

    String inputLine;

    while ((inputLine = in.readLine()) != null)
        System.out.println(inputLine);

    in.close();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM