使用 org.apache.http 发送带有 SOAP 操作的 HTTP Post 请求
Posted
技术标签:
【中文标题】使用 org.apache.http 发送带有 SOAP 操作的 HTTP Post 请求【英文标题】:Sending HTTP Post request with SOAP action using org.apache.http 【发布时间】:2012-05-27 03:23:47 【问题描述】:我正在尝试使用 org.apache.http api 编写带有 SOAP 操作的硬编码 HTTP Post 请求。 我的问题是我没有找到添加请求正文的方法(在我的情况下 - 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();
【问题讨论】:
你写的代码在哪里 【参考方案1】:这是一个完整的工作示例:
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);
【讨论】:
我正在尝试您的代码并收到此异常:java.net.SocketException: Software caused connection abort: recv failed
。我的类路径中有 httpclient-4.5.2.jar 和 httpcore-4.4.4.jar。有什么想法吗?【参考方案2】:
这是我尝试过的示例,它对我有用:
创建 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);
【讨论】:
【参考方案3】:它给出了 415 Http 响应代码作为错误,
所以我加了
httppost.addHeader("Content-Type", "text/xml; charset=utf-8");
现在一切正常,Http:200
【讨论】:
你能解释一下为什么添加这个有助于解决错误吗?【参考方案4】:在通过 java 客户端调用 WCF 服务时,识别需要在 soap 操作上设置什么的最简单方法是加载 wsdl,转到与服务匹配的操作名称。从那里获取操作 URI 并将其设置在肥皂操作标头中。你已经完成了。
例如:来自 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);
【讨论】:
【参考方案5】:... using org.apache.http api. ...
您需要在请求中包含SOAPAction
作为标头。由于您有httpPost
和requestWrapper
句柄,因此可以通过三种方式添加标题。
1. httpPost.addHeader( "SOAPAction", strReferenceToSoapActionValue );
2. httpPost.setHeader( "SOAPAction", strReferenceToSoapActionValue );
3. requestWrapper.setHeader( "SOAPAction", strReferenceToSoapActionValue );
唯一的区别是addHeader
允许多个具有相同标头名称的值,而setHeader
仅允许唯一标头名称。 setHeader(...
over 写入同名的第一个标头。
您可以根据自己的要求使用其中任何一种。
【讨论】:
@Ravinder 你能看看我朋友的问题吗:***.com/questions/12827900/…【参考方案6】:soapAction 必须作为 http-header 参数传递 - 使用时,它不是 http-body/payload 的一部分。
在这里查看使用 apache httpclient 的示例:http://svn.apache.org/repos/asf/httpcomponents/oac.hc3x/trunk/src/examples/PostSOAP.java
【讨论】:
你能看看我朋友的问题吗:***.com/questions/12827900/…以上是关于使用 org.apache.http 发送带有 SOAP 操作的 HTTP Post 请求的主要内容,如果未能解决你的问题,请参考以下文章
卡夫卡连接错误:java.lang.NoClassDefFoundError:org/apache/http/conn/HttpClientConnectionManager
Android Studio使用org.apache.http报错
从 org.apache.http.HttpResponse 获取 HTTP 代码