Httpclient调用Util

Httpclient调用Util

maven配置

 
  1. <dependency>
  2. <groupId>com.alibaba</groupId>
  3. <artifactId>fastjson</artifactId>
  4. <version>1.2.46</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>org.apache.httpcomponents</groupId>
  8. <artifactId>httpclient</artifactId>
  9. <version>4.3.1</version>
  10. </dependency>

主要核心代码

GET方法

 
  1. private static JSONObject sendAlaudaData(String url){
  2. JSONObject jsonObject= null;
  3. try {
  4. HttpGet httpGet = new HttpGet(DEFAULT_HOST_URL+url);
  5. httpGet.setHeader("Authorization", DEFAULT_TOKEN);
  6. httpGet.setHeader("Content-Type", "application/json; charset=utf-8");
  7. HttpClient client = HttpClients.createDefault();
  8. HttpResponse httpResponse = client.execute(httpGet);
  9. String respContent = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
  10. jsonObject = JSONObject.parseObject(respContent);
  11. } catch (UnsupportedEncodingException e) {
  12. e.printStackTrace();
  13. } catch (IOException e) {
  14. e.printStackTrace();
  15. }
  16. return jsonObject;
  17. }

POST方法

 
  1. /**
  2. * HttpClient link
  3. * @param jsonBody
  4. * @param url
  5. * @return
  6. */
  7. private static JSONObject sendAlaudaData(String jsonBody,String url) {
  8. JSONObject jsonObject = null;
  9. try {
  10. HttpPost httpPost = new HttpPost(DEFAULT_HOST_URL+url);
  11. StringEntity entity = new StringEntity(jsonBody, "UTF-8");
  12. httpPost.setHeader("Authorization", DEFAULT_TOKEN);
  13. httpPost.setHeader("Content-Type", "application/json; charset=utf-8");
  14. httpPost.setEntity(entity);
  15. HttpClient client = HttpClients.createDefault();
  16. HttpResponse httpResponse = client.execute(httpPost);
  17. String respContent = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
  18. Object object = JSONObject.parse(respContent);
  19. if(object instanceof JSONObject){
  20. jsonObject= (JSONObject)object;
  21. }else if(object instanceof JSONArray){
  22. jsonObject =((JSONArray) object).getJSONObject(0);
  23. }
  24. } catch (UnsupportedEncodingException e) {
  25. e.printStackTrace();
  26. } catch (IOException e) {
  27. e.printStackTrace();
  28. }
  29. return jsonObject;
  30. }

最后奉上完整代码

 
  1. import com.alibaba.fastjson.JSONArray;
  2. import com.alibaba.fastjson.JSONObject;
  3. import com.irootech.service.dto.SUserDTO;
  4. import org.apache.http.HttpResponse;
  5. import org.apache.http.client.HttpClient;
  6. import org.apache.http.client.methods.HttpGet;
  7. import org.apache.http.client.methods.HttpPost;
  8. import org.apache.http.entity.StringEntity;
  9. import org.apache.http.impl.client.HttpClients;
  10. import org.apache.http.util.EntityUtils;
  11. import java.io.IOException;
  12. import java.io.UnsupportedEncodingException;
  13. public class AlaudaAPI {
  14. private final static String DEFAULT_HOST_URL = "http://<host>";
  15. private final static String DEFAULT_TOKEN = "Token....";
  16. private final static String DEFAULT_CLUSTER = "test";
  17. private final static String APPS_URL = "apps";
  18. private final static String SPACE = "-space";
  19. private final static String ROLE = "-role";
  20. public static void main(String[] args) {
  21. /*JSONObject result = getRoleDetail("tes2t");
  22. System.out.println("========"+result.getJSONArray("errors"));*/
  23. String jsonN = "{\"username\": \"test_5\", \"password\": \"123456\"}";
  24. Object jsonObject = JSONObject.parse(jsonN);
  25. if(jsonObject instanceof JSONObject){
  26. JSONObject jsonObject1 = (JSONObject)jsonObject;
  27. System.out.println(jsonObject1);
  28. }else if(jsonObject instanceof JSONArray){
  29. JSONObject jsonObject2 =((JSONArray) jsonObject).getJSONObject(0);
  30. System.out.println(jsonObject2);
  31. }
  32. System.out.println(jsonObject);
  33. }
  34. /**
  35. * HttpClient link
  36. * @param jsonBody
  37. * @param url
  38. * @return
  39. */
  40. private static JSONObject sendAlaudaData(String jsonBody,String url) {
  41. JSONObject jsonObject = null;
  42. try {
  43. HttpPost httpPost = new HttpPost(DEFAULT_HOST_URL+url);
  44. StringEntity entity = new StringEntity(jsonBody, "UTF-8");
  45. httpPost.setHeader("Authorization", DEFAULT_TOKEN);
  46. httpPost.setHeader("Content-Type", "application/json; charset=utf-8");
  47. httpPost.setEntity(entity);
  48. HttpClient client = HttpClients.createDefault();
  49. HttpResponse httpResponse = client.execute(httpPost);
  50. String respContent = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
  51. Object object = JSONObject.parse(respContent);
  52. if(object instanceof JSONObject){
  53. jsonObject= (JSONObject)object;
  54. }else if(object instanceof JSONArray){
  55. jsonObject =((JSONArray) object).getJSONObject(0);
  56. }
  57. } catch (UnsupportedEncodingException e) {
  58. e.printStackTrace();
  59. } catch (IOException e) {
  60. e.printStackTrace();
  61. }
  62. return jsonObject;
  63. }
  64. /**
  65. * 创建角色和资源空间
  66. * @param tentanId 目前由tentanId创建角色和命名空间
  67. * @return
  68. */
  69. private static JSONObject createRoleResource(String tentanId){
  70. String url = "/v1/roles/alauda";
  71. String roleName = tentanId+ROLE;
  72. String spaceName = tentanId+SPACE;
  73. String jsonBody = "{\"name\": \"" + roleName + "\",\"parents\": [],\"permissions\": [{\"resource_type\": \"application\",\"constraints\": [{\"res:cluster\": \"*\",\"res:space\": \"" + spaceName + "\"}],\"actions\": [\"application:*\"],\"resource\": [\"*\"]},{\"resource_type\": \"service\",\"constraints\": [],\"actions\": [\"service:*\"],\"resource\": [\"*\"]},{\"resource_type\": \"cluster\",\"constraints\": [],\"actions\": [\"cluster:*\"],\"resource\": [\"*\"]},{\"resource_type\": \"cluster_node\",\"constraints\": [],\"actions\": [\"cluster_node:*\"],\"resource\": [\"*\"]},{\"resource_type\": \"namespace\",\"constraints\": [],\"actions\": [\"namespace:*\"],\"resource\": [\"*\"]}]}";
  74. JSONObject respContent = sendAlaudaData(jsonBody,url);
  75. return respContent;
  76. }
  77. /**
  78. * 创建用户调用灵雀灵
  79. * @param jsonUser
  80. * @return
  81. */
  82. private static JSONObject createUser(String jsonUser) {
  83. String url = "/v1/orgs/alauda/accounts";
  84. //jsonUser = "{\"roles\": [{\"name\": \"-1-space\",\"uuid\": \"6803dff4-6f6f-40b6-8f96-df751062afd8\"}],\"password\": \"123456\",\"position\": \"研发工程师\",\"mobile\": \"155xxxx4501\",\"extra_info\": \"test\",\"realname\": \"xq\",\"email\": \"xxx@xx.com\",\"landline_phone\": \"010-88xx345\",\"department\": \"研发部\",\"usernames\": [\"002-space\"],\"office_address\": \"中关村大街3号\"}";
  85. JSONObject resultUser=sendAlaudaData(jsonUser,url);
  86. return resultUser;
  87. }
  88. /**
  89. * 给用户分配角色(如果创建用户时指定角色,可不调用此方法)
  90. * @param userName
  91. * @param roleName
  92. * @return
  93. */
  94. private static JSONObject assignRoleForUser(String userName, String roleName) {
  95. String url = "/v1/orgs/alauda/accouts/" + userName + "/roles";
  96. String jsonBody="[{\"name\": \"" + roleName + "\"}]";
  97. JSONObject respContent = sendAlaudaData(jsonBody,url);
  98. return respContent;
  99. }
  100. /**
  101. * 创建用户
  102. * @param tentanId
  103. * @param sUserVM
  104. * @return
  105. */
  106. public static JSONObject createUser(String tentanId,SUserDTO sUserVM){
  107. /* 查询当前角色是否已存在 */
  108. JSONObject jsonRole = getRoleDetail(tentanId);
  109. JSONArray error = jsonRole.getJSONArray("errors");
  110. /*如果查询不到结构,将返回error错误,出现error说明角色尚未创建走else*/
  111. if(error==null){
  112. /* 用户信息转换到JSON */
  113. JSONObject userJson=userToJson(jsonRole,sUserVM);
  114. return createUser(userJson.toString());
  115. }else{
  116. jsonRole = createRoleResource(tentanId);
  117. JSONObject userJson=userToJson(jsonRole,sUserVM);
  118. return createUser(userJson.toString());
  119. }
  120. }
  121. /**
  122. * 根据用户信息封装json格式数据
  123. * @param jsonRole
  124. * @param sUserVM
  125. * @return
  126. */
  127. public static JSONObject userToJson(JSONObject jsonRole,SUserDTO sUserVM) {
  128. JSONObject jsonObject = new JSONObject();
  129. JSONArray jsonArray = new JSONArray();
  130. jsonObject.put("password", "123456");
  131. jsonObject.put("mobile", sUserVM.getTelphone());
  132. jsonObject.put("email", sUserVM.getEmail());
  133. jsonObject.put("realname", sUserVM.getName());
  134. jsonObject.put("department", sUserVM.getIdentityName());
  135. jsonObject.put("office_address", "");
  136. jsonObject.put("landline_phone", "");
  137. jsonObject.put("department", "开发部");
  138. jsonArray.add(sUserVM.getLoginName());
  139. jsonObject.put("usernames", jsonArray);
  140. /*封装角色信息*/
  141. String uuid = (String) jsonRole.get("uuid");
  142. String name = (String) jsonRole.get("name");
  143. jsonRole = new JSONObject();
  144. jsonRole.put("uuid", uuid);
  145. jsonRole.put("name", name);
  146. jsonArray = new JSONArray();
  147. jsonArray.add(jsonRole);
  148. jsonObject.put("roles", jsonArray);
  149. return jsonObject;
  150. }
  151. private static JSONObject sendAlaudaData(String url){
  152. JSONObject jsonObject= null;
  153. try {
  154. HttpGet httpGet = new HttpGet(DEFAULT_HOST_URL+url);
  155. httpGet.setHeader("Authorization", DEFAULT_TOKEN);
  156. httpGet.setHeader("Content-Type", "application/json; charset=utf-8");
  157. HttpClient client = HttpClients.createDefault();
  158. HttpResponse httpResponse = client.execute(httpGet);
  159. String respContent = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
  160. jsonObject = JSONObject.parseObject(respContent);
  161. } catch (UnsupportedEncodingException e) {
  162. e.printStackTrace();
  163. } catch (IOException e) {
  164. e.printStackTrace();
  165. }
  166. return jsonObject;
  167. }
  168. /**
  169. * 查询角色是否存在
  170. * @param roleName
  171. * @return
  172. */
  173. private static JSONObject getRoleDetail(String roleName) {
  174. String nameSpaceName = "alauda"; //命名空间目前固定是 alauda
  175. String url = "/v1/roles/" + nameSpaceName + "/" + roleName+ROLE;
  176. JSONObject requestBody = sendAlaudaData(url);
  177. return requestBody;
  178. }
  179. }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值