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接口调用并解决登陆保持会话功能的更多相关文章

  1. Java:concurrent包下面的Map接口框架图(ConcurrentMap接口、ConcurrentHashMap实现类)

    Java集合大致可分为Set.List和Map三种体系,其中Set代表无序.不可重复的集合:List代表有序.重复的集合:而Map则代表具有映射关系的集合.Java 5之后,增加了Queue体系集合, ...

  2. Java:concurrent包下面的Collection接口框架图( CopyOnWriteArraySet, CopyOnWriteArrayList,ConcurrentLinkedQueue,BlockingQueue)

    Java集合大致可分为Set.List和Map三种体系,其中Set代表无序.不可重复的集合:List代表有序.重复的集合:而Map则代表具有映射关系的集合.Java 5之后,增加了Queue体系集合, ...

  3. Function接口 – Java8中java.util.function包下的函数式接口

    Introduction to Functional Interfaces – A concept recreated in Java 8 Any java developer around the ...

  4. 开源免费的天气预报接口API以及全国所有地区代码(国家气象局提供)

    天气预报一直是各大网站的一个基本功能,最近小编也想在网站上弄一个,得瑟一下,在网络搜索了很久,终于找到了开源免费的天气预报接口API以及全国所有地区代码(国家气象局提供),具体如下: 国家气象局提供的 ...

  5. 开放数据接口 API 简介与使用场景、调用方法

    此文章对开放数据接口 API 进行了功能介绍.使用场景介绍以及调用方法的说明,供用户在使用数据接口时参考之用. 在给大家分享的一系列软件开发视频课程中,以及在我们的社区微信群聊天中,都积极地鼓励大家开 ...

  6. 分享淘宝时间服务器同步时间接口api和苏宁时间服务器接口api

    最近要开发一款抢购秒杀的小工具,需要同步系统时间,这里分享两个时间服务器接口api给大家: 1.淘宝时间服务器时间接口 http://api.m.taobao.com/rest/api3.do?api ...

  7. Atitit 图像处理之编程之类库调用的接口api cli gui ws rest  attilax大总结.docx

    Atitit 图像处理之编程之类库调用的接口api cli gui ws rest  attilax大总结.docx 1. 为什么需要接口调用??1 1.1. 为了方便集成复用模块类库1 1.2. 嫁 ...

  8. 服务端调用接口API利器之HttpClient

    前言 之前有介绍过HttpClient作为爬虫的简单使用,那么今天在简单的介绍一下它的另一个用途:在服务端调用接口API进行交互.之所以整理这个呢,是因为前几天在测试云之家待办消息接口的时候,有使用云 ...

  9. PHP调用百度天气接口API

    //百度天气接口API $location = "北京"; //地区 $ak = "5slgyqGDENN7Sy7pw29IUvrZ"; //秘钥,需要申请,百 ...

随机推荐

  1. asp.net服务控件的生命周期

    1. 初始化 - Init事件 (OnInit 方法)   2. 加载视图状态 - LoadViewState方法   3. 处理回发数据 - LoadPostData方法           对实现 ...

  2. NSDate获取当前时区的时间

    [NSDate date]获取的是GMT时间,要想获得某个时区的时间,以下代码可以解决这个问题 NSDate *date = [NSDate date]; NSTimeZone *zone = [NS ...

  3. [Android Studio] 按钮学习

    Android Studio 按钮 1. 添加一个按钮 新建一个 Blank Project 之后, 在 activity_main.xml: 中添加一个按钮, 可以使用design 模式来添加,: ...

  4. 2016年12月19日 星期一 --出埃及记 Exodus 21:14

    2016年12月19日 星期一 --出埃及记 Exodus 21:14 But if a man schemes and kills another man deliberately, take hi ...

  5. CSS 定位

    一.CSS 定位和浮动   它们代替了多年来的表格布局.   定位的思想很简单,相对于正常位置.相对于父元素.另一个元素甚至是浏览器窗口的位置.   浮动在 CSS1 中被首次提出.浮动不完全是定位, ...

  6. sql基本操作

    SQL功能 数据查询 SELECT 数据定义 CREATE,  DROP,   ALTER 数据操纵 INSERT,   UPDATE,   DELETE 数据控制 GRANT,  REVOKE 创建 ...

  7. Cheatsheet: 2016 02.01 ~ 02.29

    Web How to do distributed locking Writing Next Generation Reusable JavaScript Modules in ECMAScript ...

  8. C#程序设计---->计算圆面积windows程序

    值得说的就是添加一个回车事件, http://blog.csdn.net/nanwang314/article/details/6176604 private void textBox1_KeyDow ...

  9. psd切图

    打开UI设计师给你的PSD文件,我们以下图为例,截产品超市前面的购物车 1.按v选择移动工具,然后在上面的选项栏中勾选自动选择,在再右边选择图层 2.这时候用鼠标选中产品超市前面的购物车,就能在右边的 ...

  10. CSS的压缩 方法与解压

    为什么要压缩CSS? 1.大网站节约流量 2.加快访问速度 工具:Dreamweaver(手工替换,个人感觉任何文本编辑器都可以)不过DW可以还原 CSS压缩与CSS代码压缩还原方法,CSS压缩工具有 ...