首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网站开发 > Web前端 >

施用HttpClient 4.1.2调用webservice

2012-09-13 
使用HttpClient 4.1.2调用webservice下载httpclient,把压缩包里lib目录的所有jar放到项目的编译目录里,通

使用HttpClient 4.1.2调用webservice
下载httpclient,把压缩包里lib目录的所有jar放到项目的编译目录里,
通过Post方式调用webservice,代码如下:

import java.io.IOException;import java.io.UnsupportedEncodingException;import org.apache.http.HttpEntity;import org.apache.http.HttpResponse;import org.apache.http.client.ClientProtocolException;import org.apache.http.client.methods.HttpPost;import org.apache.http.entity.StringEntity;import org.apache.http.impl.client.DefaultHttpClient;import org.apache.http.protocol.HTTP;import org.apache.http.util.EntityUtils;public class HttpclientSoap {public static void main(String[] args){DefaultHttpClient httpClient = new DefaultHttpClient();String soapRequestData = "<?xml version="1.0" encoding="utf-8"?>" +"<soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">"  +  "<soap12:Body>" +   " <SetData xmlns="http://tempuri.org/">" +     " <dz>宁波海曙市</dz>" +    "  <id>27000</id>" +    "  <xx>27000</xx>" +    "  <yy>13112</yy>" +    "  <bui_id>4209</bui_id>" +    "  <mc>天一数码</mc>" +    "</SetData>" + " </soap12:Body>" +"</soap12:Envelope>" ;HttpPost httppost = new HttpPost("http://localhost/Service1.asmx");/*把Soap请求数据添加到PostMethod*///byte[] b = soapRequestData.getBytes("utf-8");//InputStream is = new ByteArrayInputStream(b,0,b.length);try {HttpEntity re = new StringEntity(soapRequestData,HTTP.UTF_8);httppost.setHeader("Content-Type","application/soap+xml; charset=utf-8");//httppost.setHeader("Content-Length", String.valueOf(soapRequestData.length()));httppost.setEntity(re);HttpResponse response = httpClient.execute(httppost);System.out.println(EntityUtils.toString(httppost.getEntity()));System.out.println(response.getStatusLine());System.out.println(EntityUtils.toString(response.getEntity()));} catch (UnsupportedEncodingException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (ClientProtocolException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}finally{httpClient.getConnectionManager().shutdown();}}}

热点排行