httpclient 3.1和4.1 请求的区别

本文详细对比了HTTP客户端3.1与4.1在进行POST请求时的不同实现方式,并通过代码示例展示了如何使用这两个版本的库来模拟Web服务请求。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Httpclient 3.1和httpclient 4.1 在post请求中的不同。
下面的示例将httpclient请求模拟webservices请求。


3.1 包名:commons-httpclient-3.1.jar

public static EnvelopeDocument call(String soapString, String endpoint, int timeout)
throws SOAException
{
EnvelopeDocument resDoc = null;
PostMethod post = null;
HttpClient httpclient = new HttpClient();
try
{
HttpClientParams params = new HttpClientParams();
params.setSoTimeout(timeout * 1000);
httpclient.setParams(params);
post = new PostMethod(endpoint);
org.apache.commons.httpclient.methods.RequestEntity entity = new StringRequestEntity(soapString, "text/xml", "UTF-8");
post.setRequestEntity(entity);
int result = httpclient.executeMethod(post);
String res;
if(result != 200)
{
res = post.getResponseBodyAsString();
throw new SOAException(ErrorCode.CALL_WEB_SERVICE_ERROR, "Web Service Server returns HTTP code " + result + "\n" + res);
}
res = post.getResponseBodyAsString();
try
{
resDoc = org.xmlsoap.schemas.soap.envelope.EnvelopeDocument.Factory.parse(res);
}
catch(XmlException xe)
{
throw new SOAException(ErrorCode.PARSE_RESPONSE_XML_ERROR, "Parsing web service response soap message error", xe);
}
}
catch(SOAException e)
{
e.printStackTrace();
throw e;
}
catch(Exception e)
{
e.printStackTrace();
throw new SOAException(ErrorCode.CALL_WEB_SERVICE_ERROR, "call web service error" + e.getMessage(), e);
}
return resDoc;
}



4.1 包名:httpclient-4.1.jar

public static String requestWebservice(String url, String xmlParam)
throws ClientProtocolException, IOException {
Validate.notNull(url, "请求url");
Validate.notNull(xmlParam, "符合webservice标准的xml字符串");

String responseContent = "";

HttpClient httpClient = new DefaultHttpClient();
byte[] b = xmlParam.getBytes("utf-8");
HttpPost httpPost = new HttpPost(url);
if (url.indexOf("RushRepairService") != -1) {
b = xmlParam.getBytes("GBK");
}
InputStream is = new ByteArrayInputStream(b, 0, b.length);
HttpEntity re = new InputStreamEntity(is, b.length);
httpPost.setEntity(re);

HttpResponse response = httpClient.execute(httpPost);

if (200 != response.getStatusLine().getStatusCode()) {
throw new RuntimeException("http返回状态"
+ response.getStatusLine().getStatusCode());
}

HttpEntity entity = response.getEntity();

String inputLine = "";
InputStreamReader in = new InputStreamReader(entity.getContent());
BufferedReader reader = new BufferedReader(in);
while ((inputLine = reader.readLine()) != null) {
responseContent += inputLine;
}
reader.close();

httpClient.getConnectionManager().shutdown();
return responseContent;
}



如有任何疑问可扫码头像关注公众号!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值