标签:
xmlrpc 、 https 、 cookies 、 httpclient、bugzilla 、 java实现加密通信下的xmlrpc接口调用并解决登陆保持会话功能,网上针对bugzilla的实现很少,针对xmlrpc的有但是基本都是http协议的,https下的认证处理比较麻烦,而且会话保持也是基本没有太多共享,所以本人决定结合xmlrpc\bugzilla官方文档,网友文章,结合个人经验总结而成,已经在window2007 64+jdk7位机器上调试通过
手把手教你如何实现:
第一步:
在eclipse中创建一个maven工程,在POM.xml文件中 <dependencies>与</dependencies>之间添加rpc的依赖包 (如果不是maven工程,直接去下载jar包引入即可):
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>javax.xml.rpc</artifactId>
<version>3.2-b06</version>
</dependency>
第二步: 新建一个基础类BugzillaRPCUtil.java,进行基本的ssl认证处理,参数封装、调用封装等
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.apache.xmlrpc.XmlRpcException;
import org.apache.xmlrpc.XmlRpcRequest;
import org.apache.xmlrpc.client.XmlRpcClient;
import org.apache.xmlrpc.client.XmlRpcClientConfigImpl;
import org.apache.xmlrpc.client.XmlRpcClientException;
import org.apache.xmlrpc.client.XmlRpcSunHttpTransport;
import org.apache.xmlrpc.client.XmlRpcTransport;
import org.apache.xmlrpc.client.XmlRpcTransportFactory;
public class BugzillaRPCUtil
{
private static XmlRpcClient client = null;
// Very simple cookie storage
private final static LinkedHashMap<String, String> cookies = new LinkedHashMap<String, String>();
private HashMap<String, Object> parameters = new HashMap<String, Object>();
private String command;
// path to Bugzilla XML-RPC interface
//注意https://bugzilla.tools.vipshop.com/bugzilla/这部分的URL要更换成你自己的域名地址,还有bugzilla的账户和密码
private static final String serverUrl = "https://bugzilla.tools.vipshop.com/bugzilla/xmlrpc.cgi";
/**
* Creates a new instance of the Bugzilla XML-RPC command executor for a specific command
*
* @param command A remote method associated with this instance of RPC call executor
*/
public BugzillaRPCUtil(String command)
{
synchronized (this)
{
this.command = command;
if (client == null)
{ // assure the initialization is done only once
client = new XmlRpcClient();
XmlRpcClientConfigImpl config = new XmlRpcClientConfigImpl();
try
{
config.setServerURL(new URL(serverUrl));
}
catch (MalformedURLException ex)
{
Logger.getLogger(BugzillaRPCUtil.class.getName()).log(Level.SEVERE, null, ex);
}
XmlRpcTransportFactory factory = new XmlRpcTransportFactory()
{
public XmlRpcTransport getTransport()
{
return new XmlRpcSunHttpTransport(client)
{
private URLConnection conn;
@Override
protected URLConnection newURLConnection(URL pURL)
throws IOException
{
conn = super.newURLConnection(pURL);
return conn;
}
@Override
protected void initHttpHeaders(XmlRpcRequest pRequest)
throws XmlRpcClientException
{
super.initHttpHeaders(pRequest);
setCookies(conn);
}
@Override
protected void close()
throws XmlRpcClientException
{
getCookies(conn);
}
private void setCookies(URLConnection pConn)
{
String cookieString = "";
for (String cookieName : cookies.keySet())
{
cookieString += "; " + cookieName + "=" + cookies.get(cookieName);
}
if (cookieString.length() > 2)
{
setRequestHeader("Cookie", cookieString.substring(2));
}
}
private void getCookies(URLConnection pConn)
{
String headerName = null;
for (int i = 1; (headerName = pConn.getHeaderFieldKey(i)) != null; i++)
{
if (headerName.equals("Set-Cookie"))
{
String cookie = pConn.getHeaderField(i);
cookie = cookie.substring(0, cookie.indexOf(";"));
String cookieName = cookie.substring(0, cookie.indexOf("="));
String cookieValue = cookie.substring(cookie.indexOf("=") + 1, cookie.length());
cookies.put(cookieName, cookieValue);
}
}
}
};
}
};
client.setTransportFactory(factory);
client.setConfig(config);
}
}
}
/**
* Get the parameters of this call, that were set using setParameter method
*
* @return Array with a parameter hashmap
*/
protected Object[] getParameters()
{
return new Object[] {parameters};
}
/**
* Set parameter to a given value
*
* @param name Name of the parameter to be set
* @param value A value of the parameter to be set
* @return Previous value of the parameter, if it was set already.
*/
public Object setParameter(String name, Object value)
{
return this.parameters.put(name, value);
}
/**
* Executes the XML-RPC call to Bugzilla instance and returns a map with result
*
* @return A map with response
* @throws XmlRpcException
*/
public Map execute()
throws XmlRpcException
{
return (Map)client.execute(command, this.getParameters());
}
public static void initSSL()
throws Exception
{
// Create a trust manager that does not validate certificate chains
TrustManager[] trustAllCerts = new TrustManager[] {new X509TrustManager()
{
public X509Certificate[] getAcceptedIssuers()
{
return null;
}
public void checkClientTrusted(X509Certificate[] certs, String authType)
{
// Trust always
}
public void checkServerTrusted(X509Certificate[] certs, String authType)
{
// Trust always
}
}};
// Install the all-trusting trust manager
SSLContext sc = SSLContext.getInstance("SSL");
// Create empty HostnameVerifier
HostnameVerifier hv = new HostnameVerifier()
{
public boolean verify(String arg0, SSLSession arg1)
{
return true;
}
};
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
HttpsURLConnection.setDefaultHostnameVerifier(hv);
}
}
第三步: 新建一个接口调用类BugzillaLoginCall.java实现登陆,继承BugzillaRPCUtil类
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.xmlrpc.XmlRpcException;
public class BugzillaLoginCall extends BugzillaRPCUtil
{
/**
* Create a Bugzilla login call instance and set parameters
*/
public BugzillaLoginCall(String username, String password)
{
super("User.login");
setParameter("login", username);
setParameter("password", password);
}
/**
* Perform the login action and set the login cookies
*
* @returns True if login is successful, false otherwise. The method sets Bugzilla login cookies.
*/
public static boolean login(String username, String password)
{
Map result = null;
try
{
// the result should contain one item with ID of logged in user
result = new BugzillaLoginCall(username, password).execute();
}
catch (XmlRpcException ex)
{
Logger.getLogger(BugzillaLoginCall.class.getName()).log(Level.SEVERE, null, ex);
}
// generally, this is the place to initialize model class from the result map
return !(result == null || result.isEmpty());
}
}
第三=四步: 新建一个接口调用类BugzillaGetUserCall.java实现查询用户信息,继承BugzillaRPCUtil类
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.xmlrpc.XmlRpcException;
public class BugzillaGetUserCall extends BugzillaRPCUtil
{
/**
* Create a Bugzilla login call instance and set parameters
*/
public BugzillaGetUserCall(String ids)
{
super("User.get");
setParameter("ids", ids);
// setParameter("password", password);
}
/**
* Perform the login action and set the login cookies
*
* @returns True if login is successful, false otherwise. The method sets Bugzilla login cookies.
*/
public static Map getUserInfo(String ids)
{
Map result = null;
try
{
// the result should contain one item with ID of logged in user
result = new BugzillaGetUserCall(ids).execute();
}
catch (XmlRpcException ex)
{
Logger.getLogger(BugzillaLoginCall.class.getName()).log(Level.SEVERE, null, ex);
}
// generally, this is the place to initialize model class from the result map
return result;
}
}
第五步: 新建一个运行类BugzillaAPI.java,并输出返回结果
import java.util.HashMap;
import java.util.Map;
/**
* 20150608
*
* @author sea.zeng
*
*/
public class BugzillaAPI
{
@SuppressWarnings({"rawtypes"})
public static void main(String[] args)
throws Exception
{
String username = new String("你的bugzilla账号");
String password = new String("你的bugzilla密码");
BugzillaRPCUtil.initSSL();
boolean r = BugzillaLoginCall.login(username, password);
System.out.println("r=" + r);
String ids = new String("1603");
Map map = (HashMap)BugzillaGetUserCall.getUserInfo(ids);
// id real_name email name
System.out.println(map.toString());
Object usersObject = map.get("users");
System.out.println(usersObject.toString());
Object[] usersObjectArray = (Object[])usersObject;
Map userMap = (HashMap)usersObjectArray[0];
System.out.println(userMap.toString());
Map r2 = userMap;
System.out.println("r2.id=" + r2.get("id") + ",r2.real_name=" + r2.get("real_name") + ",r2.email="
+ r2.get("email") + ",r2.name=" + r2.get("name"));
}
}
本着资源共享的原则,欢迎各位朋友在此基础上完善,并进一步分享,让我们的实现更加优雅。如果有任何疑问和需要进一步交流可以加我QQ 1922003019或者直接发送QQ邮件给我沟通
sea 20150608 中国:广州: VIP
标签:
原文地址:http://www.cnblogs.com/sea520/p/4561707.html