用java调用https webservice,该怎么处理
1个回答
展开全部
public String sendPost(String url, String param) {
String requestData = param;//参数
String requsetString = url;//远程接口地址
// First create a trust manager that won't care.
//信任任何证书
X509TrustManager trustManager = new X509TrustManager() {
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
// Don't do anything.
}
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
// Don't do anything.
}
public X509Certificate[] getAcceptedIssuers() {
// Don't do anything.
return null;
}
};
// 把信任证书放到ssl中
SSLContext sslcontext;
String result = "";
try {
sslcontext = SSLContext.getInstance("SSL");
sslcontext.init(null, new TrustManager[] {trustManager}, null);
// Use the above SSLContext to create your socket factory
// (I found trying to extend the factory a bit difficult due to a
// call to createSocket with no arguments, a method which doesn't
// exist anywhere I can find, but hey-ho).
SSLSocketFactory sf = new SSLSocketFactory(sslcontext);
sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
DefaultHttpClient httpclient = new DefaultHttpClient();
httpclient.getConnectionManager().getSchemeRegistry().register(new Scheme("https", sf, VariableTool.HTTP_NUM));
HttpPost httpPost = new HttpPost(requsetString);
// 执行https请求
httpPost.setHeader("Authorization", "basic " + "dGNsb3VkYWRtaW46dGNsb3VkMTIz");
httpPost.setHeader("Content-type", "application/xml");
StringEntity reqEntity;
// 将请求参数封装成HttpEntity
reqEntity = new StringEntity(requestData,"UTF-8");
BufferedHttpEntity bhe = new BufferedHttpEntity(reqEntity);
httpPost.setEntity(bhe);
HttpResponse response = httpclient.execute(httpPost);
HttpEntity resEntity = response.getEntity();
InputStreamReader reader = new InputStreamReader(resEntity.getContent());
char[] buff = new char[1024];
int length = 0;
while ((length = reader.read(buff)) != -1) {
result += new String(buff, 0, length);
}
logger.debug("调用ws接口返回:" + result);
httpclient.getConnectionManager().shutdown();
} catch (Exception e) {
e.printStackTrace();
return "";
}
return result;
}
result 就是远程接口返回的接口
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询