Tag Archives: web service

java httpclient 读取sharepoint restful web service

使用java读取sharepoint 的web service 有点麻烦,麻烦的地方主要是用户验证。 sharepoint主要用的是NTLM验证方式,微软在2008年之前从来没有公布任何关于NTLM验证的文档,所以JAVA对NTLM的支持不如.net

好在httpclient 对NTLM 有一些支持,但是官方不对这段代码负责,请看这里http://hc.apache.org/httpcomponents-client-ga/ntlm.html

一段比较完整的代码请看这里

 

PrintWriter out = ServletActionContext.getResponse().getWriter();
			DefaultHttpClient httpclient = new DefaultHttpClient();
			httpclient.getCredentialsProvider().setCredentials(
				    new AuthScope("test.sharepoint", 80), 
				    new NTCredentials("userame", "password", "MYSERVER", "domain"));
			
			ResponseHandler<String> responseHandler = new BasicResponseHandler();
			String smsURL = "http://test.sharepoint/_vti_bin/listdata.svc/testList";
			try {
				HttpGet httpget = new HttpGet(smsURL);
				httpget.setHeader("accept", "application/json");
				String responseBody2 = StringUtils.chomp(httpclient.execute(
						httpget, responseHandler));
				System.out.println(responseBody2);
				out.print(responseBody2);
			} catch (ClientProtocolException e) {
				log.error(e, e);
			} catch (IOException e) {
				log.error(e, e);
			} finally {
				httpclient.getConnectionManager().shutdown();
			}

稍微解释一下:httpget.setHeader("accept", "application/json"); 是为了让sharepoint 的web service 返回json的数据格式。 sharepoint 默认会返回atom 格式的数据。详情请阅读:http://msdn.microsoft.com/zh-cn/library/ff521587(v=office.14).aspx

cxf NTLM 客户端验证(Spring 配置)

FormServiceSoap cs = (FormServiceSoap) ctx.getBean("client");
Client client = ClientProxy.getClient("http://10.188.12.7/formservice.asmx?wsdl");
HTTPConduit http = (HTTPConduit) client.getConduit();
HTTPClientPolicy httpClientPolicy = new HTTPClientPolicy();
httpClientPolicy.setConnectionTimeout(36000);
httpClientPolicy.setAllowChunking(false);
http.setClient(httpClientPolicy);
http.getAuthorization().setAuthorizationType("NTLM");
http.getAuthorization().setUserName("xxxx");
http.getAuthorization().setPassword("xxxxx");
URL wsdlURL = FormService.WSDL_LOCATION;
#boolean port = cs.createSystemError("123", "456", "789", "0123", true); 这个是我用cxf自动生成的一个web service方法
System.out.println(port);

主要spring 配置文件

<bean id="client" class="org.tempuri.FormServiceSoap"
        factory-bean="clientFactory" factory-method="create" />

    <bean id="clientFactory"
        class="org.apache.cxf.jaxws.JaxWsProxyFactoryBean">
        <property name="serviceClass" value="org.tempuri.FormServiceSoap" />
        <property name="address" value="http://sharepoint/formservice.asmx?wsdl" />
    </bean>