bugzilla4的xmlrpc接口api调用实现分享: xmlrpc + https + cookies + httpclient +bugzilla + java实现加密通信下的xmlrpc接口调用并解决登陆保持会话功能
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
bugzilla4的xmlrpc接口api调用实现分享: xmlrpc + https + cookies + httpclient +bugzilla + java实现加密通信下的xmlrpc接口调用并解决登陆保持会话功能的更多相关文章
- Java:concurrent包下面的Map接口框架图(ConcurrentMap接口、ConcurrentHashMap实现类)
Java集合大致可分为Set.List和Map三种体系,其中Set代表无序.不可重复的集合:List代表有序.重复的集合:而Map则代表具有映射关系的集合.Java 5之后,增加了Queue体系集合, ...
- Java:concurrent包下面的Collection接口框架图( CopyOnWriteArraySet, CopyOnWriteArrayList,ConcurrentLinkedQueue,BlockingQueue)
Java集合大致可分为Set.List和Map三种体系,其中Set代表无序.不可重复的集合:List代表有序.重复的集合:而Map则代表具有映射关系的集合.Java 5之后,增加了Queue体系集合, ...
- Function接口 – Java8中java.util.function包下的函数式接口
Introduction to Functional Interfaces – A concept recreated in Java 8 Any java developer around the ...
- 开源免费的天气预报接口API以及全国所有地区代码(国家气象局提供)
天气预报一直是各大网站的一个基本功能,最近小编也想在网站上弄一个,得瑟一下,在网络搜索了很久,终于找到了开源免费的天气预报接口API以及全国所有地区代码(国家气象局提供),具体如下: 国家气象局提供的 ...
- 开放数据接口 API 简介与使用场景、调用方法
此文章对开放数据接口 API 进行了功能介绍.使用场景介绍以及调用方法的说明,供用户在使用数据接口时参考之用. 在给大家分享的一系列软件开发视频课程中,以及在我们的社区微信群聊天中,都积极地鼓励大家开 ...
- 分享淘宝时间服务器同步时间接口api和苏宁时间服务器接口api
最近要开发一款抢购秒杀的小工具,需要同步系统时间,这里分享两个时间服务器接口api给大家: 1.淘宝时间服务器时间接口 http://api.m.taobao.com/rest/api3.do?api ...
- Atitit 图像处理之编程之类库调用的接口api cli gui ws rest attilax大总结.docx
Atitit 图像处理之编程之类库调用的接口api cli gui ws rest attilax大总结.docx 1. 为什么需要接口调用??1 1.1. 为了方便集成复用模块类库1 1.2. 嫁 ...
- 服务端调用接口API利器之HttpClient
前言 之前有介绍过HttpClient作为爬虫的简单使用,那么今天在简单的介绍一下它的另一个用途:在服务端调用接口API进行交互.之所以整理这个呢,是因为前几天在测试云之家待办消息接口的时候,有使用云 ...
- PHP调用百度天气接口API
//百度天气接口API $location = "北京"; //地区 $ak = "5slgyqGDENN7Sy7pw29IUvrZ"; //秘钥,需要申请,百 ...
随机推荐
- 错误,这个如何解决呢?内存溢出的问提。把JAVA_OPTS="-server -XX:PermSize=64M -XX:MaxPermSize=128m 还是不行
java.lang.OutOfMemoryError: PermGen space at java.lang.ClassLoader.defineClass1(Native Method) at ja ...
- 关于JQ的$.deferred函数。参考网络文档
由于jQuery版本问题对Deferred对象的实现有所不同,具体请参照jQuery api: jQuery.Deferred()基于Promises/A规范实现,因为jQuery本身的设计风格, ...
- Flowplayer-Subtitle
SOURCE URL: https://flowplayer.org/docs/subtitles.html Setting up Subtitles are loaded with a <tr ...
- ArcGIS Javascript地图上添加json数据格式的点
/** * 显示地图点. * json的格式[{"name":"name1","x":"x1","y" ...
- Android知识散点
1.所有活动都需要在AndroidMainfest.xml中注册后才能生效. <activity android:name=".MainActivity" android:l ...
- 4 .Swift函数|闭包
在编程中,我们常把能完成某一特定功能的一组代码,并且带有名字标记类型叫做函数,在C语言中,我们知道函数名就是一个指针,它指向了函数体内代码区的第一行代码的地址,在swift中也具有同样的功效. 在Sw ...
- WPF-非矩形窗口的创建
第一.窗口的AllowsTransparency设置为True 第二.窗口的Background设置为Transparent 第三.窗口的WindowStyle设置为None 第四.窗口内的Grid用 ...
- 将回车键转tab键
//功能:将回车键转tab键$(function () {$('input:text:first').focus();var $enter = $("input[type=text],but ...
- OpenCV图像处理中常用函数汇总(2)
// 霍夫线变换 hough vector<Vec2f> lines;//定义一个矢量结构lines用于存放得到的线段矢量集合 HoughLines(dstImage,lines,,CV_ ...
- 安卓手机上运行 PC-E500 程序
目录 第1章安卓手机上运行 PC-E500 程序 1 1 PockEmul 1 2 下载 1 3 打包BASIC程序 2 4 配置PC-E500模拟器 5 5 载入e50 ...