Java HttpClient 4.3.1 访问ASP.NET WebService

首先下载HttpClient 4.3.1的jar包,下载地址:http://mirrors.hust.edu.cn/apache//httpcomponents/httpclient/binary/httpcomponents-client-4.3.1-bin.zip

依赖Jar包文件:commons-codec-1.6.jar,httpclient-4.3.1.jar,httpcore-4.3.jar,另外,需要额外加入log4j-1.2.16.jar及commons-logging-1.1.3.jar包。

示例代码如下:

package com.project.ws;

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.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;


public class WSClient {
	public static final String WSDLURL = "http://127.0.0.1:8080/Test.asmx?wsdl";
	public static void main(String[] args){
		HttpClient client = HttpClients.createDefault();
		String reqSoapData = buildReqSoapData();
		HttpPost post = new HttpPost(WSDLURL);
		try {
			HttpEntity re = new StringEntity(reqSoapData,"UTF-8");
			post.setHeader("Content-Type","application/soap+xml; charset=UTF-8");
			//post.setHeader("Content-Length", String.valueOf(reqSoapData.length()));
			post.setEntity(re);			
			HttpResponse response = client.execute(post);
			System.out.println("请求服务的Soap文本:"+EntityUtils.toString(post.getEntity()));
			System.out.println("请求服务结果状态:"+response.getStatusLine());
			System.out.println("请求服务返回XML文本:"+EntityUtils.toString(response.getEntity()));			
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
	
	/**
	 * 生成请求服务的Soap XML字符串
	 * @return String
	 */
	public static String buildReqSoapData(){
		String soapData = "";
		soapData += "<?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>" +
		   " <getStudentInfo xmlns=\"http://tempuri.org/\">" +
		     " <strKey>person</strKey>" +
		    "  <strwhere>name='花无影'</strwhere>" +
		    "</getStudentInfo>" +
		 " </soap12:Body>" +
		"</soap12:Envelope>" ;
		return soapData;
	}
}

 说明:其中生成请求的Soap文本中,

<getStudentInfo xmlns="http://tempuri.org/">

<strKey>person</strKey>

<strwhere>name='花无影'</strwhere>

</getStudentInfo>,

getStudentInfo为方法名称,strKey及strwhere为参数名称,对应的值为参数的值。

 

转载于:https://my.oschina.net/4k9LCGA/blog/168291

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值