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

HttpClient调用.net发布的带Windows NTML验证的webservice

2016-03-17 10:31 841 查看


使用HttpClient调用:

先要通过Windows NTML验证,然后才能调用 。

class  WebServiceTest
{

/**
* 获取接口数据
* @param soapRequest
* @return String
*/
public String postSoapRequest(String soapRequest){
CloseableHttpClient httpclient =  HttpClients.createDefault();
//Windows NTLM验证
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(AuthScope.ANY,
new NTCredentials(InterfaceConstants.THE_USERNAME,
InterfaceConstants.THE_PASSWORD,
InterfaceConstants.THE_HOST,
System.getenv("userdomain")));
HttpHost target = new HttpHost(InterfaceConstants.THE_HOST, 80, "http");
HttpClientContext context = HttpClientContext.create();
context.setCredentialsProvider(credsProvider);
HttpGet httpget = new HttpGet(InterfaceConstants.THE_URL);
CloseableHttpResponse response1 = null;
try {
response1 = httpclient.execute(target, httpget, context);
}catch(Exception e){
e.printStackTrace();
}finally {
try {
response1.close();
} catch (IOException e) {
e.printStackTrace();
}
}
//使用相同的上下文,执行重量级的方法
HttpPost httppost = new HttpPost(InterfaceConstants.THE_URL);
HttpEntity re = new StringEntity(soapRequest, "utf-8");
httppost.setHeader("Content-Type","text/xml; charset=utf-8");
httppost.setEntity(re);
CloseableHttpResponse response2 = null;
String  result = null;//返回结果
try {
response2 = httpclient.execute(target, httppost, context);
HttpEntity entity2 = response2.getEntity();
if (entity2 != null) {
//响应内容
result = EntityUtils.toString(entity2, "utf-8");
System.out.println("isChunked:"+entity2.isChunked());
}
}catch(Exception e) {
e.printStackTrace();
} finally {
try {
response2.close();
} catch (IOException e){
e.printStackTrace();
}
}
return result;
}

@Test
public void testHelloWorld()throws Exception {
/*soap请求*/
String soapRequest = "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
+"<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""
+" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" "
+" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"
+" <soap:Body>"
+"  <HelloWorld xmlns=\"http://tempuri.org/\"/>"
+"  </soap:Body>"
+"</soap:Envelope>";

String res = postSoapRequest(soapRequest);//调用

/*处理返回的结果*/
Document document = DocumentHelper.parseText(res);
Element root = document.getRootElement();
Element body = root.element("Body");
Element responseEle = body.element("HelloWorldResponse");
Element resultEle = responseEle.element("HelloWorldResult");
System.out.println(resultEle.getData());

}
}

/**接口相关信息*/
public interface InterfaceConstants {

public static final String THE_URL = "http://xxxxxxxxervice.asmx";
/**
* 用户名
*/
public static final String THE_USERNAME = "xxxxx";
/**
* 加密后密码
*/
public static final String THE_PASSWORD = "xxxxx";
/**
* 接口host
*/
public static final String THE_HOST= "xxxxxxxxxxxxx";
/**
* 接口地址
*/
public static final String THE_URL="http://xxxxxxxxervice.asmx";

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: