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