我正在尝试将 XML 文件作为 Http POST 请求传递。当我在 Linux 机器上使用 CURL 进行测试时,Web 服务工作正常,并且 XML 格式良好。我正在尝试编写一个 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);
怎么了?请帮忙。
最佳答案
您在类路径中错过了 apache commons-logging.jar
。下载它并将其添加到您的类路径中。
更新:
现在您需要下载并添加commons-codec.jar
。
关于java - HttpClient 版本 3.1 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25433240/