您的位置:首页 > 理论基础 > 计算机网络

httpclient 3.1和4.1 请求的区别

2014-02-17 11:55 309 查看
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;
}



如有任何疑问可扫码头像关注公众号!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: