`
zjnbshifox
  • 浏览: 312542 次
  • 性别: Icon_minigender_1
  • 来自: 宁波
社区版块
存档分类
最新评论

使用HttpClient 4.1.2调用webservice

    博客分类:
  • Java
 
阅读更多
下载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 block
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			httpClient.getConnectionManager().shutdown();
		}
		
	}
}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics