我正在尝试将XML文件作为Http POST请求传递。当我在Linux机器上使用CURL测试它并且XML格式正确时,webservice工作正常。我正在尝试编写一个Java实用程序来执行相同的操作。我在Apache Commons HttpClient库3.1版中找到了一个示例,这是我的代码:
进口:
import java.io.File;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.FileRequestEntity;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
代码:
String strURL = "https://localhost/scoring";
String strXMLFilename = "C:\\Users\\Test.xml";
File input = new File(strXMLFilename);
PostMethod post = new PostMethod(strURL);
RequestEntity entity = new FileRequestEntity(input, "text/xml; charset=ISO--");
post.setRequestEntity(entity);
Get HTTP client
HttpClient httpclient = new HttpClient();
try
{
int result = httpclient.executeMethod(post);
System.out.println("Response status code: " + result);
System.out.println("Response body: ");
System.out.println(post.getResponseBodyAsString());
}
finally
{
post.releaseConnection();
}
我收到错误:
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory
at org.apache.commons.httpclient.HttpMethodBase.<clinit>(HttpMethodBase.java:104)
at Test.main(Test.java:40)
更新
添加了Commons-logging-1.2.jar
仍然出错:
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/codec/DecoderException
at org.apache.commons.httpclient.HttpMethodBase.<init>(HttpMethodBase.java:220)
at org.apache.commons.httpclient.methods.ExpectContinueMethod.<init>(ExpectContinueMethod.java:93)
at org.apache.commons.httpclient.methods.EntityEnclosingMethod.<init>(EntityEnclosingMethod.java:119)
at org.apache.commons.httpclient.methods.PostMethod.<init>(PostMethod.java:106)
at Test.main(Test.java:40)
Caused by: java.lang.ClassNotFoundException: org.apache.commons.codec.DecoderException
它抛出这一行:
PostMethod post = new PostMethod(strURL);
什么错了?请帮忙。
答案 0 :(得分:2)
你错过了类路径中的apache commons-logging.jar
。下载并将其添加到类路径中。
更新:
现在您需要commons-codec.jar
下载并添加它。
答案 1 :(得分:1)
你只需要将Apache Commons Logging jar添加到你的类路径中(如果你使用的是IDE你的项目库)你可以从here下载它。
答案 2 :(得分:0)
我已经通过导入以下依赖项解决了这个问题
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
<exclusions>
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>*</artifactId>
</exclusion>
</exclusions>
</dependency>