import java.io.bufferedreader; import java.io.bytearrayoutputstream; import java.io.file; import java.io.fileoutputstream; import java.io.ioexception; import java.io.inputstream; import java.io.inputstreamreader; import java.io.printwriter; import java.net.url; import java.net.urlconnection; import java.util.arraylist; import java.util.date; import java.util.hashmap; import java.util.linkedhashmap; import java.util.list; import java.util.map; import java.util.set; import java.util.concurrent.executorservice; import java.util.concurrent.executors; import org.apache.commons.io.ioutils; import org.apache.http.httpentity; import org.apache.http.namevaluepair; 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.entity.contenttype; import org.apache.http.entity.stringentity; import org.apache.http.entity.mime.multipartentitybuilder; import org.apache.http.entity.mime.content.filebody; import org.apache.http.entity.mime.content.stringbody; import org.apache.http.impl.client.closeablehttpclient; import org.apache.http.impl.client.httpclients; import org.apache.http.message.basicnamevaluepair; import org.apache.http.util.entityutils; import com.google.gson.jsonarray; import com.google.gson.jsonobject; import com.google.gson.jsonparser; public class httpclientutil { public static final int thread_pool_size = 5; public interface httpclientdownloadprogress { public void onprogress(int progress); } private static httpclientutil httpclientdownload; private executorservice downloadexcutorservice; private httpclientutil() { downloadexcutorservice = executors.newfixedthreadpool(thread_pool_size); } public static httpclientutil getinstance() { if (httpclientdownload == null) { httpclientdownload = new httpclientutil(); } return httpclientdownload; } /** * @param url * @param filepath */ public void download(final string url, final string filepath) { downloadexcutorservice.execute(new runnable() { @override public void run() { httpdownloadfile(url, filepath, null, null); } }); } /** * * @param url * @param filepath * @param progress */ public void download(final string url, final string filepath, final httpclientdownloadprogress progress) { downloadexcutorservice.execute(new runnable() { @override public void run() { httpdownloadfile(url, filepath, progress, null); } }); } /** * @param url * @param filepath */ private void httpdownloadfile(string url, string filepath, httpclientdownloadprogress progress, mapheadmap) { closeablehttpclient httpclient = httpclients.createdefault(); try { httpget httpget = new httpget(url); setgethead(httpget, headmap); closeablehttpresponse response1 = httpclient.execute(httpget); try { system.out.println(response1.getstatusline()); httpentity httpentity = response1.getentity(); long contentlength = httpentity.getcontentlength(); inputstream is = httpentity.getcontent(); bytearrayoutputstream output = new bytearrayoutputstream(); byte[] buffer = new byte[4096]; int r = 0; long totalread = 0; while ((r = is.read(buffer)) > 0) { output.write(buffer, 0, r); totalread = r; if (progress != null) { progress.onprogress((int) (totalread * 100 / contentlength)); } } fileoutputstream fos = new fileoutputstream(filepath); output.writeto(fos); output.flush(); output.close(); fos.close(); entityutils.consume(httpentity); } finally { response1.close(); } } catch (exception e) { e.printstacktrace(); } finally { try { httpclient.close(); } catch (ioexception e) { e.printstacktrace(); } } } /** * @param url * @return */ public string httpget(string url) { return httpget(url, null); } /** * http get * * @param url * @return */ public string httpget(string url, map headmap) { string responsecontent = null; closeablehttpclient httpclient = httpclients.createdefault(); try { httpget httpget = new httpget(url); closeablehttpresponse response1 = httpclient.execute(httpget); setgethead(httpget, headmap); try { httpentity entity = response1.getentity(); responsecontent = getrespstring(entity); entityutils.consume(entity); } finally { response1.close(); } } catch (exception e) { e.printstacktrace(); } finally { try { httpclient.close(); } catch (ioexception e) { e.printstacktrace(); } } return responsecontent; } public string httppost(string url, map paramsmap) { return httppost(url, paramsmap, null); } /** * @param url * @param paramsmap * @return */ public string httppost(string url, map paramsmap, map headmap) { string responsecontent = null; closeablehttpclient httpclient = httpclients.createdefault(); try { httppost httppost = new httppost(url); setposthead(httppost, headmap); setpostparams(httppost, paramsmap); closeablehttpresponse response = httpclient.execute(httppost); try { httpentity entity = response.getentity(); responsecontent = getrespstring(entity); entityutils.consume(entity); } finally { response.close(); } } catch (exception e) { e.printstacktrace(); } finally { try { httpclient.close(); } catch (ioexception e) { e.printstacktrace(); } } return responsecontent; } /** * @param httppost * @param headmap */ private void setposthead(httppost httppost, map headmap) { if (headmap != null && headmap.size() > 0) { set keyset = headmap.keyset(); for (string key : keyset) { httppost.addheader(key, headmap.get(key)); } } } /** * * * @param httpget * @param headmap */ private void setgethead(httpget httpget, map headmap) { if (headmap != null && headmap.size() > 0) { set keyset = headmap.keyset(); for (string key : keyset) { httpget.addheader(key, headmap.get(key)); } } } /** * * * @param serverurl ַ * @param localfilepath * * @param serverfieldname * @param params * @return * @throws exception */ public string uploadfileimpl(string serverurl, string localfilepath, string serverfieldname, map params, map paramshead) throws exception { string respstr = null; closeablehttpclient httpclient = httpclients.createdefault(); try { httppost httppost = new httppost(serverurl); setposthead(httppost, paramshead); filebody binfilebody = new filebody(new file(localfilepath)); multipartentitybuilder multipartentitybuilder = multipartentitybuilder.create(); multipartentitybuilder.addpart(serverfieldname, binfilebody); setuploadparams(multipartentitybuilder, params); httpentity reqentity = multipartentitybuilder.build(); httppost.setentity(reqentity); closeablehttpresponse response = httpclient.execute(httppost); try { httpentity resentity = response.getentity(); respstr = getrespstring(resentity); entityutils.consume(resentity); } finally { response.close(); } } finally { httpclient.close(); } return respstr; } /** * @param multipartentitybuilder * @param params */ private void setuploadparams(multipartentitybuilder multipartentitybuilder, map params) { if (params != null && params.size() > 0) { set keys = params.keyset(); for (string key : keys) { multipartentitybuilder.addpart(key, new stringbody(params.get(key), contenttype.application_json)); } } } /** * string * * @param entity * @return * @throws exception */ private string getrespstring(httpentity entity) throws exception { if (entity == null) { return null; } inputstream is = entity.getcontent(); stringbuffer strbuf = new stringbuffer(); byte[] buffer = new byte[4096]; int r = 0; while ((r = is.read(buffer)) > 0) { strbuf.append(new string(buffer, 0, r, "utf-8")); } return strbuf.tostring(); } /** * @param httppost * @param paramsmap * @throws exception */ private void setpostparams(httppost httppost, map paramsmap) throws exception { if (paramsmap != null && paramsmap.size() > 0) { list nvps = new arraylist (); set keyset = paramsmap.keyset(); for (string key : keyset) { nvps.add(new basicnamevaluepair(key, paramsmap.get(key))); } httppost.setentity(new urlencodedformentity(nvps)); } } public static string sendpost(string url, string token, string paramsstr) throws ioexception, exception { // post请求 closeablehttpclient httpclient = httpclients.createdefault(); // 请求参数 stringentity postingstring = new stringentity(paramsstr, "utf-8"); httppost httppost = new httppost(url); httppost.setentity(postingstring); // 请求头设置 httppost.addheader("cookie", "x-token=" token); httppost.addheader("accept", "*/*"); httppost.addheader("connection", "keep-alive"); httppost.addheader("content-type", "application/json; charset=utf-8"); httppost.addheader("user-agent", "mozilla/4.0 (compatible; msie 6.0; windows nt 5.1;sv1)"); // 执行请求 closeablehttpresponse execute = httpclient.execute(httppost); // 处理返回结果 string reststr = ioutils.tostring(execute.getentity().getcontent(), "utf-8"); return reststr; } public static string sendpost(string url, string param) { printwriter out = null; bufferedreader in = null; string result = ""; try { url realurl = new ; urlconnection conn = realurl.openconnection(); conn.setrequestproperty("accept", "*/*"); conn.setrequestproperty("connection", "keep-alive"); conn.setrequestproperty("content-type", "application/json; charset=utf-8"); conn.setrequestproperty("user-agent", "mozilla/4.0 (compatible; msie 6.0; windows nt 5.1;sv1)"); conn.setdooutput(true); conn.setdoinput(true); out = new printwriter(conn.getoutputstream()); out.print(param); out.flush(); in = new bufferedreader(new inputstreamreader(conn.getinputstream())); string line; while ((line = in.readline()) != null) { result = line; } } catch (exception e) { system.out.println(" post" e); e.printstacktrace(); } finally { try { if (out != null) { out.close(); } if (in != null) { in.close(); } } catch (ioexception ex) { ex.printstacktrace(); } } return result; } public static void main(string[] args) throws ioexception, exception { string token = ""; // 第一步:单点登入 string path = "http://127.0.0.1:20020/x_organization_assemble_authentication/jaxrs/sso"; // 单点路径 long time = new date().gettime(); // 当前时间 string login_uid = "kfry"; // 用户id string sso_key = "12345678"; // 加密密码 string xtoken = null; string client = "sso"; // sso配置名称 try { xtoken = crypto.encrypt(login_uid "#" time, sso_key); system.out.println(xtoken); } catch (exception e1) { e1.printstacktrace(); } string string = "{"token": " xtoken ", "client": " client "}"; string str = httpclientutil.getinstance().sendpost(path, string); jsonparser parser = new jsonparser(); jsonobject object = null; object = (jsonobject) parser.parse(str); jsonobject value = object.get("data").getasjsonobject(); token = value.get("token").getasstring(); // 第二步:创建流程 string processid = "e4c77038-2964-498f-9d37-1635e26639eb";// 流程id path = "http://127.0.0.1:20020/x_processplatform_assemble_surface/jaxrs/work/process/" processid;// 流程创建路径 string datagrid = "{"data": [{" " " " "col1": { "textfield1": "1" }," " "col2": { "textfield2": "2" }," " "col3": { "textfield3": "3" }," " "col4": { "textfield4": "4" }," " "col5": { "textfield5": "5" }" " }," " {" " "col1": { "textfield1": "11" }," " "col2": { "textfield2": "12" }," " "col3": { "textfield3": "13" }," " "col4": { "textfield4": "14" }," " "col5": { "textfield5": "15" }" " }]}"; // 数据网格数据 jsonparser parser1 = new jsonparser(); jsonobject jsonobj = parser1.parse(datagrid).getasjsonobject(); jsonobject jsonobject = new jsonobject(); jsonobject.addproperty("latest", false); jsonobject.addproperty("title", "演示系统grid测试(2021-02-22)");// 标题 jsonobject.addproperty("identity", "开发人员@932ca9a4-4c80-4a29-9e44-aed85afe21d3@i"); // 创建者身份 jsonobject jsonobjectdata = new jsonobject(); jsonobjectdata.addproperty("subject", "演示系统grid测试2021-02-22"); // 标题 jsonobjectdata.addproperty("calendar", "2020-04-13 12:00:00");// 表单 上的字段名“calendar” jsonobjectdata.addproperty("explain", "演示系统grid测试"); // 表单 上的字段名“explain” jsonobjectdata.add("datagrid", jsonobj); // 表单上的数据网格 jsonobject.add("data", jsonobjectdata); // 创建流程 string strflow = httpclientutil.getinstance().sendpost(path, token, jsonobject.tostring()); string work = ""; // 获取返回的workid jsonparser parser2 = new jsonparser(); jsonobject object2 = null; object2 = (jsonobject) parser2.parse(strflow); jsonarray value2 = object2.getasjsonarray("data"); object2 = value2.get(0).getasjsonobject(); work = object2.get("work").getasstring(); system.out.println("work=" work); // 上传附件 try { map uploadparams = new linkedhashmap (); uploadparams.put("filename", "明天.docx"); // 附件名 uploadparams.put("site", "attachment"); // 表单上的附件控件标识 uploadparams.put("extraparam", ""); map headmap = new hashmap (); headmap.put("cookie", "x-token=" token); // 单点token headmap.put("accept", "*/*"); headmap.put("connection", "keep-alive"); headmap.put("user-agent", "mozilla/4.0 (compatible; msie 6.0; windows nt 5.1;sv1)"); string atturl = "http://127.0.0.1:20020/x_processplatform_assemble_surface/jaxrs/attachment/upload/work/" work; string filepath = "f:download明天.docx"; httpclientutil.getinstance().uploadfileimpl(atturl, filepath, "file", uploadparams, headmap); } catch (exception e) { e.printstacktrace(); } } }
二、功能代码介绍
第一步:单点登入
一、创建sso配置,请参考组织管理里中的sso管理
二、通过下面代码获取token.
注意:下面代码中要调整的内容如下:
“path”:单点路径要根据实际服务器ip调整;
“login_uid”:单点用户id;
“sso_key”:加密解密密码;
“client”:sso配置名称;
string token = ""; //第一步:单点登入 string path = "http://127.0.0.1:20020/x_organization_assemble_authentication/jaxrs/sso"; //单点路径 long time = new date().gettime(); //当前时间 string login_uid = "kfry"; //用户id string sso_key = "12345678"; //加密密码 string xtoken = null; string client = "sso"; //sso配置名称 try { xtoken = crypto.encrypt( login_uid "#" time, sso_key ); system.out.println(xtoken); } catch (exception e1) { e1.printstacktrace(); } string string = "{"token": " xtoken ", "client": " client "}"; string str = httpclientutil.getinstance().sendpost(path,string); jsonparser parser = new jsonparser(); jsonobject object = null; object =(jsonobject) parser.parse(str); jsonobject value =object.get("data").getasjsonobject(); token= value.get("token").getasstring();
第二步:创建流程
一、设置x-token
注意:下面代码中要调整的内容如下:
“processid”: 流程id;
“path”:创建流程路径要根据实际服务器ip调整;
“title”:标题;
“identity”:创建者身份;
“subject”:标题;
...... // 第二步:创建流程 string processid = "e4c77038-2964-498f-9d37-1635e26639eb";// 流程id path = "http://127.0.0.1:20020/x_processplatform_assemble_surface/jaxrs/work/process/";// 流程创建路径 string datagrid = "{"data": [{" " " " "col1": { "textfield1": "1" }," " "col2": { "textfield2": "2" }," " "col3": { "textfield3": "3" }," " "col4": { "textfield4": "4" }," " "col5": { "textfield5": "5" }" " }," " {" " "col1": { "textfield1": "11" }," " "col2": { "textfield2": "12" }," " "col3": { "textfield3": "13" }," " "col4": { "textfield4": "14" }," " "col5": { "textfield5": "15" }" " }]}"; // 数据网格数据 jsonparser parser1 = new jsonparser(); jsonobject jsonobj = parser1.parse(datagrid).getasjsonobject(); jsonobject jsonobject = new jsonobject(); jsonobject.addproperty("latest", false); jsonobject.addproperty("title", "演示系统grid测试(2021-02-22)");// 标题 jsonobject.addproperty("identity", "开发人员@932ca9a4-4c80-4a29-9e44-aed85afe21d3@i"); // 创建者身份 jsonobject jsonobjectdata = new jsonobject(); jsonobjectdata.addproperty("subject", "演示系统grid测试2021-02-22"); // 标题 jsonobjectdata.addproperty("calendar", "2020-04-13 12:00:00");// 表单 上的字段名“calendar” jsonobjectdata.addproperty("explain", "演示系统grid测试"); // 表单 上的字段名“explain” jsonobjectdata.add("datagrid", jsonobj); // 表单上的数据网格 jsonobject.add("data", jsonobjectdata); // 创建流程 string strflow = httpclientutil.getinstance().sendpost(path, token, jsonobject.tostring()); string work = ""; // 获取返回的workid jsonparser parser2 = new jsonparser(); jsonobject object2 = null; object2 = (jsonobject) parser2.parse(strflow); jsonarray value2 = object2.getasjsonarray("data"); object2 = value2.get(0).getasjsonobject(); work = object2.get("work").getasstring(); ......
第三步:上传附件
一、设置x-token
二、设置workid
注意:下面代码中要调整的内容如下:
“filename”:附件名
“site”:表单上的附件控件标识
“filepath”:附件路径
“atturl”:附件接口要根据实际服务器ip调整
// 上传附件 try { mapuploadparams = new linkedhashmap (); uploadparams.put("filename", "明天.docx"); // 附件名 uploadparams.put("site", "attachment"); // 表单上的附件控件标识 uploadparams.put("extraparam", ""); map headmap = new hashmap (); headmap.put("cookie", "x-token=" token); // 单点token headmap.put("accept", "*/*"); headmap.put("connection", "keep-alive"); headmap.put("user-agent", "mozilla/4.0 (compatible; msie 6.0; windows nt 5.1;sv1)"); string atturl = "http://127.0.0.1:20020/x_processplatform_assemble_surface/jaxrs/attachment/upload/work/" work; string filepath = "f:download明天.docx"; httpclientutil.getinstance().uploadfileimpl(atturl, filepath, "file", uploadparams, headmap); } catch (exception e) { e.printstacktrace(); }
若有收获,就点个赞吧