禅道接口是http接口,本文使用的是httpclient调用禅道接口
一、获取操作的sessionID
禅道api相关操作都需要登录后才能进行(请求需要携带登录完成cookie),请求地址http://127.0.0.1/zentao/api-getsessionid.json。
二、登录禅道
请求地址http://127.0.0.1/zentao/user-login.json,需要携带的参数用户名account,密码password,上一步获取的zentaosid,此步骤进行过后返回的cookie需要储存起来,后面需要使用。
三、查询某用户
请求地址http://127.0.0.1/zentao/user-view-[用户名].json,携带上一步登录后产生的cookie进行请求,否则请求无法成功。
四、创建用户
创建用户为最复杂的地方
1、先获取禅道创建用户的必要属性。
①、先在此界面手动添加一次用户
②、在浏览器的开发者模式下查看创建用户的参数,然后我们发现其中的password1,password2,verifyPassword为加密后的数值。
2、获取创建用户时密码的加密规则
①、在浏览器的开发者模式下查看创建用户界面的js方法发现password1,password2加密方法为一样的,verifyPassword为另一种加密方法。
②、获取rand变量,通过上一步发现密码的加密离不开一个名为rand的变量,通过查看页面发现rand值的获取来自创建用户界面的input框。但此input框的值每次访问都会发生变化,所以每次创建用户时都要先获取这个input框的值(我们可以通过使用java发送http请求,来获取整个界面,获取input框的值)。
③、获取禅道的md5加密方法,我们再创建用户界面会看到这样一个md5.js,此js中包含的就是禅道的md5加密方法。
3、使用java调用。所以需要的参数都获取到了,可以通过java发送http请求,将参数使用form-data方式发送至http://127.0.0.1/zentao/user-create-0.json地址,即可成功创建用户
五、示例代码(本地测试)
1、引用jar包
2、代码(经测试可行)
package zentao.api;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.CookieStore;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.client.LaxRedirectStrategy;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
public class ZenTaoAPITest {
/**
* 用来存取cookies信息的变量.
*/
private static CookieStore cookieStore;
private static String jsScript;
public static void main(String[] args) {
String session=doGet("http://127.0.0.1/zentao/api-getsessionid.json", null,false);
JsonParser parse =new JsonParser();
JsonObject jsonSession = (JsonObject) parse.parse(session);
System.out.println("Session: "+jsonSession);
JsonObject jsonObj = (JsonObject) parse.parse(jsonSession.get("data").getAsJsonPrimitive().getAsString());
String sessionID=jsonObj.get("sessionID").toString();
System.out.println("sessionID: "+jsonObj.get("sessionID"));
Map
map.put("account", "admin");
map.put("password", "123456");
map.put("zentaosid", sessionID);
String login = doGet("http://127.0.0.1/zentao/user-login.json",map,true);
System.out.println("login :"+login);
String user=doGet("http://127.0.0.1/zentao/user-view-admin.json", null,true);
System.out.println("user :"+user);
System.out.println("userLength : "+user.length());
String rand=getHtmlRand("http://127.0.0.1/zentao/user-create-0.html");
// System.out.println(html);
// http://127.0.0.1/zentao/js/md5.js?v=12.3
jsScript = doGet("http://127.0.0.1/zentao/js/md5.js?v=12.3",null,true);
// System.out.println(js);
Map
params.put("dept", "1");
params.put("account", "test36");
params.put("password1", getJsMd5("123456")+rand);
params.put("password2", getJsMd5("123456")+rand);
params.put("realname", "test36");
params.put("join", "2020-04-29");
params.put("role", "qa");
params.put("group", "3");
params.put("email", "[email protected]");
params.put("commiter", "admin");
params.put("gender", "m");
params.put("verifyPassword", getJsMd5(getJsMd5("123456")+rand));
params.put("passwordStrength", "0");
System.out.println(params);
String result=doPost("http://127.0.0.1/zentao/user-create-0.json", params,true);
System.out.println(result);
}
/*
* @date: 2020年4月30日下午5:12:08
* @author: 宋
* 向指定url发起请求,可携带参数,并选择是否携带cookie
*/
public static String doGet(String url,Map
//获取httpclient客户端
CloseableHttpClient httpclient = HttpClients.createDefault();
String resultString = "";
CloseableHttpResponse response = null;
try {
URIBuilder builder = new URIBuilder(url);
if(null!=params){
for (String key:params.keySet()) {
builder.setParameter(key, params.get(key));
}
}
HttpGet get = new HttpGet(builder.build());
if(!isCookie) {
response = httpclient.execute(get);
System.out.println(response.getStatusLine());
if(200==response.getStatusLine().getStatusCode()){
HttpEntity entity = response.getEntity();
resultString = EntityUtils.toString(entity, "utf-8");
}
}else {
resultString=GetCookies(get);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if(null!=response){
try {
response.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(null!=httpclient){
try {
httpclient.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return resultString;
}
/*
* @date: 2020年4月30日下午5:09:57
* @author: 宋
* 获取登录过后的cookie 存入 cookieStore对象
*/
public static String GetCookies(HttpGet get) throws IOException {
String result = null;
try {
if(null==cookieStore) {
cookieStore = new BasicCookieStore();
}
// 获取 响应
CloseableHttpClient httpClient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
CloseableHttpResponse response = httpClient.execute(get);
result = EntityUtils.toString(response.getEntity(), "utf-8");
// // 获取cookies信息
// List
// for (Cookie cookie : cookies) {
// String name = cookie.getName();
// String value = cookie.getValue();
// System.out.println("cookies: key= "+ name + " value= " + value);
// }
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
public static String PostCookies(HttpPost Post) throws IOException {
String result = null;
try {
if(null==cookieStore) {
cookieStore = new BasicCookieStore();
}
// 获取 响应
CloseableHttpClient httpClient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
CloseableHttpResponse response = httpClient.execute(Post);
result = EntityUtils.toString(response.getEntity(), "utf-8");
// // 获取cookies信息
// List
// for (Cookie cookie : cookies) {
// String name = cookie.getName();
// String value = cookie.getValue();
// System.out.println("cookies: key= "+ name + " value= " + value);
// }
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
public static String getHtml(String url) {
URL URL = null;
HttpURLConnection conn = null;
InputStream in = null;
BufferedReader br = null;
String html = null;
try {
URL = new URL(url);
conn = (HttpURLConnection) URL.openConnection();
conn.setRequestMethod("GET");
String code = getCode(conn.getContentType());
System.out.println(code);
in = conn.getInputStream();
br = new BufferedReader(new InputStreamReader(in, code));
// 得到HTML文档
String data = "";
while ((data = br.readLine()) != null) {
html += data + "\n";
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
br.close();
in.close();
conn.disconnect();
} catch (Exception ex) {
ex.printStackTrace();
}
}
return html;
}
private static String getCode(String contentType) {
int star=contentType.indexOf("charset=");
return contentType.substring(star+8);
}
/*
* @date: 2020年4月30日下午5:15:44
* @author: 宋
* 获取html页面,并选择是否携带cookie发出请求
*/
public static String doGetHtml(String url,boolean isCookie){
//获取httpclient客户端
CloseableHttpClient httpclient = HttpClients.createDefault();
String resultString = "";
CloseableHttpResponse response = null;
try {
HttpGet get = new HttpGet(url);
if(!isCookie) {
response = httpclient.execute(get);
System.out.println(response.getStatusLine());
if(200==response.getStatusLine().getStatusCode()){
HttpEntity entity = response.getEntity();
resultString = EntityUtils.toString(entity, "utf-8");
}
}else {
resultString=GetCookies(get);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if(null!=response){
try {
response.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(null!=httpclient){
try {
httpclient.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return resultString;
}
public static String getHtmlRand(String url) {
String result=doGetHtml(url, true);
int star=result.indexOf("",star);
System.out.println("start: "+star);
System.out.println("end: "+end);
String verifyRand=result.substring(star+62,end);
System.out.println("verifyRand: "+verifyRand);
System.out.println("verifyRandlength: "+verifyRand.length());
return verifyRand;
}
public static String getJsMd5(String pwd) {
Object invoke=null;
try {
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("javascript");
engine.eval(jsScript);
Invocable in = (Invocable) engine;
invoke = in.invokeFunction("md5", pwd);
} catch (Exception e) {
// TODO: handle exception
}
System.out.println(invoke);
return invoke.toString();
}
public static String doPost(String url,Map
/**
* 在4.0及以上httpclient版本中,post需要指定重定向的策略,如果不指定则按默认的重定向策略。
*
* 获取httpclient客户端
*/
CloseableHttpClient httpclient = HttpClientBuilder.create().setRedirectStrategy( new LaxRedirectStrategy()).build();
String resultString = "";
CloseableHttpResponse response = null;
try {
HttpPost post = new HttpPost(url);
List
if(null!=params){
for (String key : params.keySet()) {
paramaters.add(new BasicNameValuePair(key,params.get(key)));
}
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity (paramaters);
post.setEntity(formEntity);
}
/**
* HTTP/1.1 403 Forbidden
* 原因:
* 有些网站,设置了反爬虫机制
* 解决的办法:
* 设置请求头,伪装浏览器
*/
post.addHeader("user-agent", "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36");
if(!isCookie) {
response = httpclient.execute(post);
System.out.println(response.getStatusLine());
if(200==response.getStatusLine().getStatusCode()){
HttpEntity entity = response.getEntity();
resultString = EntityUtils.toString(entity, "utf-8");
}
}else {
resultString=PostCookies(post);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if(null!=response){
try {
response.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(null!=httpclient){
try {
httpclient.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return resultString;
}
}