org.apache.commons.httpclient 访问需要验证的webservice的一些问题

1、httpclient验证问题

  webservice需要验证时,直接发送请求会返回 HTTP/1.1 401 Unauthorized 错误

 这时候需要设置:

        Credentials defaultcreds = new UsernamePasswordCredentials("username", "password");
        httpClient.getState().setCredentials(AuthScope.ANY, defaultcreds);

注意password为明文

2、Unsupported xstream 错误

这个需要进行设置请求类型,一般请求如下设置,此为post请求:

        byte[] b = soapRequestData.getBytes("UTF-8");
         InputStream is = new ByteArrayInputStream(b,0,b.length);
        RequestEntity re = new InputStreamRequestEntity(is,b.length,"application/xop+xml; charset=UTF-8; type=\"text/xml\"");
         postMethod.setRequestEntity(re);

3、Unbuffered entity enclosing request can not be repeated.问题

一般来说,webservice需要验证时,在httpclient请求之前需要加上上面的设置,然后使用上面的访问进行post访问时会发生此错误

此时需要将设置改为如下:

 StringRequestEntity requestEntity = new StringRequestEntity(soapRequestData,"application/xop+xml; charset=UTF-8; type=\"text/xml\"","UTF-8");
 postMethod.setRequestEntity(requestEntity);


因此使用httpclient访问需要验证的webservice时,具体代码如下

public static void post() throws Exception {
		HttpClient httpClient = new HttpClient();
		//post请求内容
		String soapRequestData ="postbody";
		// 构造HttpClient的实例
		Credentials defaultcreds = new UsernamePasswordCredentials("username", "password");
        httpClient.getState().setCredentials(AuthScope.ANY, defaultcreds);
        //webservice服务请求路径
		String url = "";
		PostMethod postMethod = new PostMethod(url);
		//使用系统提供的默认的恢复策略
		postMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
				new DefaultHttpMethodRetryHandler());
         
         StringRequestEntity requestEntity = new StringRequestEntity(soapRequestData,"application/xop+xml; charset=UTF-8; type=\"text/xml\"","UTF-8");
         postMethod.setRequestEntity(requestEntity);
         
		// 执行postMethod
		int statusCode = httpClient.executeMethod(postMethod);
		// HttpClient对于要求接受后继服务的请求,
		System.out.println("statusCode is "+statusCode);
		if (statusCode != HttpStatus.SC_OK) {
			System.err.println("Method failed: "
					+ postMethod.getStatusLine());
		}
		// 读取内容
		byte[] responseBody = postMethod.getResponseBody();
		// 处理内容
		System.out.println(new String(responseBody,"utf-8"));
	}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值