1500字范文,内容丰富有趣,写作好帮手!
1500字范文 > org.apache.commons.httpclient 访问需要验证的webservice的一些问题

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

时间:2021-03-15 22:07:29

相关推荐

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);// 执行postMethodint 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"));}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。