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"; //秘钥,需要申请,百 ...
随机推荐
- log4j.properties的配置
#初始化类中要使用的Logger对象实例:log4j.rootLogger = [ level ] , appenderName1, appenderName2, … #第一个参数是日志级别(DEBU ...
- twemproxy - Proxy Server for Redis 安装测试
1. 安装 (1) 系统环境 测试用的服务器为阿里云ECS,4核8G,CentOS6.3 64bit. 部署了3个Redis实例,监听端口号为7410,7420,7430,设置maxmemory为25 ...
- mysql之常用操作
1. 数据库介绍 什么是数据库? 数据库(Database)是按照数据结构来组织.存储和管理数据的仓库,每个数据库都有一个或多个不同的API用于创建,访问,管理,搜索和复制所保存的数据.我们也可以将数 ...
- storm配置项目
java.library.path: “/usr/local/lib:/opt/local/lib:/usr/lib”### storm.* configs are general configura ...
- SerialChat与Arduino的配合使用
最近在开发过程中,用到了Arduino开发板以及其IDE:Arduino,这个IDE使用起来很方便,编码也很简单,但有一点美中不足的是Arduino只能输出数值,不能绘图,所以就用到了另外一款串口调试 ...
- (淘宝无限适配)手机端rem布局详解(转载非原创)
从网易与淘宝的font-size思考前端设计稿与工作流 本文结合自己对网易与淘宝移动端首页html元素上的font-size这个属性的思考与学习,讨论html5设计稿尺寸以及前端与设计之间协作流程的问 ...
- iOS 圆角图片
// 开启图形上下文UIGraphicsBeginImageContextWithOptions(image.size, NO, 0);// 剪裁 UIBezierPath *path=[UIBezi ...
- 转:已知2个整形数据a,b.不使用if,?:以及其他任何条件判断的语法,找出a跟b中数据的大者。
答案: int max(int a,int b){return (a+b+abs(a-b))/2;} 类似的 请定义一个宏,比较两个数a.b的大小,不能使用大于.小于.if语句 答案: #define ...
- 用substr()截取中文出现乱码的解决方法
截取中文字符串时出现乱码(使用substr()函数) 程序一:PHP截取中文字符串方法 function msubstr($str, $start, $len) { $tmpstr = &quo ...
- android mvvm
android studio 需要gradle 1.5.0以上才支持 dependencies { classpath 'com.android.tools.build:gradle:1.5.0'} ...