Httpclient调用Util
maven配置
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.46</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.3.1</version>
</dependency>
主要核心代码
GET方法
private static JSONObject sendAlaudaData(String url){
JSONObject jsonObject= null;
try {
HttpGet httpGet = new HttpGet(DEFAULT_HOST_URL+url);
httpGet.setHeader("Authorization", DEFAULT_TOKEN);
httpGet.setHeader("Content-Type", "application/json; charset=utf-8");
HttpClient client = HttpClients.createDefault();
HttpResponse httpResponse = client.execute(httpGet);
String respContent = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
jsonObject = JSONObject.parseObject(respContent);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return jsonObject;
}
POST方法
/**
* HttpClient link
* @param jsonBody
* @param url
* @return
*/
private static JSONObject sendAlaudaData(String jsonBody,String url) {
JSONObject jsonObject = null;
try {
HttpPost httpPost = new HttpPost(DEFAULT_HOST_URL+url);
StringEntity entity = new StringEntity(jsonBody, "UTF-8");
httpPost.setHeader("Authorization", DEFAULT_TOKEN);
httpPost.setHeader("Content-Type", "application/json; charset=utf-8");
httpPost.setEntity(entity);
HttpClient client = HttpClients.createDefault();
HttpResponse httpResponse = client.execute(httpPost);
String respContent = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
Object object = JSONObject.parse(respContent);
if(object instanceof JSONObject){
jsonObject= (JSONObject)object;
}else if(object instanceof JSONArray){
jsonObject =((JSONArray) object).getJSONObject(0);
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return jsonObject;
}
最后奉上完整代码
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.irootech.service.dto.SUserDTO;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
public class AlaudaAPI {
private final static String DEFAULT_HOST_URL = "http://<host>";
private final static String DEFAULT_TOKEN = "Token....";
private final static String DEFAULT_CLUSTER = "test";
private final static String APPS_URL = "apps";
private final static String SPACE = "-space";
private final static String ROLE = "-role";
public static void main(String[] args) {
/*JSONObject result = getRoleDetail("tes2t");
System.out.println("========"+result.getJSONArray("errors"));*/
String jsonN = "{\"username\": \"test_5\", \"password\": \"123456\"}";
Object jsonObject = JSONObject.parse(jsonN);
if(jsonObject instanceof JSONObject){
JSONObject jsonObject1 = (JSONObject)jsonObject;
System.out.println(jsonObject1);
}else if(jsonObject instanceof JSONArray){
JSONObject jsonObject2 =((JSONArray) jsonObject).getJSONObject(0);
System.out.println(jsonObject2);
}
System.out.println(jsonObject);
}
/**
* HttpClient link
* @param jsonBody
* @param url
* @return
*/
private static JSONObject sendAlaudaData(String jsonBody,String url) {
JSONObject jsonObject = null;
try {
HttpPost httpPost = new HttpPost(DEFAULT_HOST_URL+url);
StringEntity entity = new StringEntity(jsonBody, "UTF-8");
httpPost.setHeader("Authorization", DEFAULT_TOKEN);
httpPost.setHeader("Content-Type", "application/json; charset=utf-8");
httpPost.setEntity(entity);
HttpClient client = HttpClients.createDefault();
HttpResponse httpResponse = client.execute(httpPost);
String respContent = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
Object object = JSONObject.parse(respContent);
if(object instanceof JSONObject){
jsonObject= (JSONObject)object;
}else if(object instanceof JSONArray){
jsonObject =((JSONArray) object).getJSONObject(0);
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return jsonObject;
}
/**
* 创建角色和资源空间
* @param tentanId 目前由tentanId创建角色和命名空间
* @return
*/
private static JSONObject createRoleResource(String tentanId){
String url = "/v1/roles/alauda";
String roleName = tentanId+ROLE;
String spaceName = tentanId+SPACE;
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\": [\"*\"]}]}";
JSONObject respContent = sendAlaudaData(jsonBody,url);
return respContent;
}
/**
* 创建用户调用灵雀灵
* @param jsonUser
* @return
*/
private static JSONObject createUser(String jsonUser) {
String url = "/v1/orgs/alauda/accounts";
//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号\"}";
JSONObject resultUser=sendAlaudaData(jsonUser,url);
return resultUser;
}
/**
* 给用户分配角色(如果创建用户时指定角色,可不调用此方法)
* @param userName
* @param roleName
* @return
*/
private static JSONObject assignRoleForUser(String userName, String roleName) {
String url = "/v1/orgs/alauda/accouts/" + userName + "/roles";
String jsonBody="[{\"name\": \"" + roleName + "\"}]";
JSONObject respContent = sendAlaudaData(jsonBody,url);
return respContent;
}
/**
* 创建用户
* @param tentanId
* @param sUserVM
* @return
*/
public static JSONObject createUser(String tentanId,SUserDTO sUserVM){
/* 查询当前角色是否已存在 */
JSONObject jsonRole = getRoleDetail(tentanId);
JSONArray error = jsonRole.getJSONArray("errors");
/*如果查询不到结构,将返回error错误,出现error说明角色尚未创建走else*/
if(error==null){
/* 用户信息转换到JSON */
JSONObject userJson=userToJson(jsonRole,sUserVM);
return createUser(userJson.toString());
}else{
jsonRole = createRoleResource(tentanId);
JSONObject userJson=userToJson(jsonRole,sUserVM);
return createUser(userJson.toString());
}
}
/**
* 根据用户信息封装json格式数据
* @param jsonRole
* @param sUserVM
* @return
*/
public static JSONObject userToJson(JSONObject jsonRole,SUserDTO sUserVM) {
JSONObject jsonObject = new JSONObject();
JSONArray jsonArray = new JSONArray();
jsonObject.put("password", "123456");
jsonObject.put("mobile", sUserVM.getTelphone());
jsonObject.put("email", sUserVM.getEmail());
jsonObject.put("realname", sUserVM.getName());
jsonObject.put("department", sUserVM.getIdentityName());
jsonObject.put("office_address", "");
jsonObject.put("landline_phone", "");
jsonObject.put("department", "开发部");
jsonArray.add(sUserVM.getLoginName());
jsonObject.put("usernames", jsonArray);
/*封装角色信息*/
String uuid = (String) jsonRole.get("uuid");
String name = (String) jsonRole.get("name");
jsonRole = new JSONObject();
jsonRole.put("uuid", uuid);
jsonRole.put("name", name);
jsonArray = new JSONArray();
jsonArray.add(jsonRole);
jsonObject.put("roles", jsonArray);
return jsonObject;
}
private static JSONObject sendAlaudaData(String url){
JSONObject jsonObject= null;
try {
HttpGet httpGet = new HttpGet(DEFAULT_HOST_URL+url);
httpGet.setHeader("Authorization", DEFAULT_TOKEN);
httpGet.setHeader("Content-Type", "application/json; charset=utf-8");
HttpClient client = HttpClients.createDefault();
HttpResponse httpResponse = client.execute(httpGet);
String respContent = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
jsonObject = JSONObject.parseObject(respContent);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return jsonObject;
}
/**
* 查询角色是否存在
* @param roleName
* @return
*/
private static JSONObject getRoleDetail(String roleName) {
String nameSpaceName = "alauda"; //命名空间目前固定是 alauda
String url = "/v1/roles/" + nameSpaceName + "/" + roleName+ROLE;
JSONObject requestBody = sendAlaudaData(url);
return requestBody;
}
}