20

org.apache.http apiを使用して、SOAPアクションを使用してハードコードされたHTTPPostリクエストを作成しようとしています。私の問題は、リクエスト本文(私の場合はSOAPアクション)を追加する方法が見つからなかったことです。いくつかのガイダンスをうれしく思います。

import java.net.URI;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.RequestWrapper;
import org.apache.http.protocol.HTTP;

public class HTTPRequest
{
    @SuppressWarnings("unused")
    public HTTPRequest()
    {
        try {
            HttpClient httpclient = new DefaultHttpClient();
            String body="DataDataData";
            String bodyLength=new Integer(body.length()).toString();
            System.out.println(bodyLength);
//          StringEntity stringEntity=new StringEntity(body);

            URI uri=new URI("SOMEURL?Param1=1234&Param2=abcd");
            HttpPost httpPost = new HttpPost(uri);
            httpPost.addHeader("Test", "Test_Value");

//          httpPost.setEntity(stringEntity);

            StringEntity entity = new StringEntity(body, "text/xml",HTTP.DEFAULT_CONTENT_CHARSET);
            httpPost.setEntity(entity);

            RequestWrapper requestWrapper=new RequestWrapper(httpPost);
            requestWrapper.setMethod("POST");
            requestWrapper.setHeader("LuckyNumber", "77");
            requestWrapper.removeHeaders("Host");
            requestWrapper.setHeader("Host", "GOD_IS_A_DJ");
//          requestWrapper.setHeader("Content-Length",bodyLength);          
            HttpResponse response = httpclient.execute(requestWrapper);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
4

6 に答える 6

11

これは完全に機能する例です:

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost; 
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

public void callWebService(String soapAction, String soapEnvBody)  throws IOException {
    // Create a StringEntity for the SOAP XML.
    String body ="<?xml version=\"1.0\" encoding=\"UTF-8\"?><SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ns1=\"http://example.com/v1.0/Records\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:SOAP-ENC=\"http://schemas.xmlsoap.org/soap/encoding/\" SOAP-ENV:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\"><SOAP-ENV:Body>"+soapEnvBody+"</SOAP-ENV:Body></SOAP-ENV:Envelope>";
    StringEntity stringEntity = new StringEntity(body, "UTF-8");
    stringEntity.setChunked(true);

    // Request parameters and other properties.
    HttpPost httpPost = new HttpPost("http://example.com?soapservice");
    httpPost.setEntity(stringEntity);
    httpPost.addHeader("Accept", "text/xml");
    httpPost.addHeader("SOAPAction", soapAction);

    // Execute and get the response.
    HttpClient httpClient = new DefaultHttpClient();
    HttpResponse response = httpClient.execute(httpPost);
    HttpEntity entity = response.getEntity();

    String strResponse = null;
    if (entity != null) {
        strResponse = EntityUtils.toString(entity);
    }
}
于 2013-05-22T19:46:45.937 に答える
6

soapActionはhttp-headerパラメーターとして渡す必要があります-使用する場合、それはhttp-body/payloadの一部ではありません。

apache httpclientの例については、こちらをご覧ください:http ://svn.apache.org/repos/asf/httpcomponents/oac.hc3x/trunk/src/examples/PostSOAP.java

于 2012-05-20T07:17:14.490 に答える
6

... using org.apache.http api. ...

SOAPActionリクエストにヘッダーとして含める必要があります。あなたが持っているようにhttpPost、そしてrequestWrapper処理するように、ヘッダーを追加する3つの方法があります。

 1. httpPost.addHeader( "SOAPAction", strReferenceToSoapActionValue );
 2. httpPost.setHeader( "SOAPAction", strReferenceToSoapActionValue );
 3. requestWrapper.setHeader( "SOAPAction", strReferenceToSoapActionValue );

唯一の違いは、addHeader同じヘッダー名で複数の値をsetHeader許可し、一意のヘッダー名のみを許可することです。setHeader(...同じ名前の最初のヘッダーを上書きします。

あなたはあなたの要件にこれらのどれでも行くことができます。

于 2012-05-20T08:14:22.267 に答える
0

Javaクライアントを介してWCFサービスを呼び出すときにsoapアクションに設定する必要があるものを特定する最も簡単な方法は、wsdlをロードし、サービスに一致する操作名に移動することです。そこからアクションURIを取得し、soapアクションヘッダーに設定します。これで完了です。

例:wsdlから

<wsdl:operation name="MyOperation">
  <wsdl:input wsaw:Action="http://tempuri.org/IMyService/MyOperation" message="tns:IMyService_MyOperation_InputMessage" />
  <wsdl:output wsaw:Action="http://tempuri.org/IMyService/MyServiceResponse" message="tns:IMyService_MyOperation_OutputMessage" />

ここで、Javaコードで、soapアクションをアクションURIとして設定する必要があります。

//The rest of the httpPost object properties have not been shown for brevity
string actionURI='http://tempuri.org/IMyService/MyOperation';
httpPost.setHeader( "SOAPAction", actionURI);
于 2015-02-05T13:56:07.170 に答える
0

エラーとして415Http応答コード与えていました。

だから私は追加しました

httppost.addHeader("Content-Type", "text/xml; charset=utf-8");

今はすべて大丈夫、Http:200

于 2015-06-02T09:32:39.010 に答える
0

これが私が試した例であり、それは私のために働いています:

XMLファイルSoapRequestFile.xmlを作成します

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:tem="http://tempuri.org/">
       <soapenv:Header/>
       <soapenv:Body>
          <tem:GetConversionRate>
             <!--Optional:-->
             <tem:CurrencyFrom>USD</tem:CurrencyFrom>
             <!--Optional:-->
             <tem:CurrencyTo>INR</tem:CurrencyTo>
             <tem:RateDate>2018-12-07</tem:RateDate>
          </tem:GetConversionRate>
       </soapenv:Body>
    </soapenv:Envelope>

そしてここにjavaのコード:

import java.io.File;
import java.io.FileInputStream;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.junit.Assert;
import org.testng.annotations.Test;

import io.restassured.path.json.JsonPath;
import io.restassured.path.xml.XmlPath;
@Test
            public void getMethod() throws Exception  {
                //wsdl file :http://currencyconverter.kowabunga.net/converter.asmx?wsdl
                File soapRequestFile = new File(".\\SOAPRequest\\SoapRequestFile.xml");

                CloseableHttpClient client = HttpClients.createDefault(); //create client
                HttpPost request = new HttpPost("http://currencyconverter.kowabunga.net/converter.asmx"); //Create the request
                request.addHeader("Content-Type", "text/xml"); //adding header
                request.setEntity(new InputStreamEntity(new FileInputStream(soapRequestFile)));
                CloseableHttpResponse response =  client.execute(request);//Execute the command

                int statusCode=response.getStatusLine().getStatusCode();//Get the status code and assert
                System.out.println("Status code: " +statusCode );
                Assert.assertEquals(200, statusCode);

                String responseString = EntityUtils.toString(response.getEntity(),"UTF-8");//Getting the Response body
                System.out.println(responseString);


                XmlPath jsXpath= new XmlPath(responseString);//Converting string into xml path to assert
                String rate=jsXpath.getString("GetConversionRateResult");
                System.out.println("rate returned is: " +  rate);



        }
于 2018-12-08T11:56:51.843 に答える