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"));
	}


你可能感兴趣的:(exception,String,webservice,url,byte,credentials)