最近因為系統(tǒng)需要,需要采用 http 調(diào)用對方的服務(wù)器接口,GET,POST 都有,記錄一下
GET 請求:
/**
* 功能描述: get 請求
* @param: [url]
* @return: JSONObject
* @auther: lsr
* @date: 2018/11/14 16:59
*/
public JSONObject doGet(String url) {
// 1.使用默認(rèn)的配置的httpclient
JSONObject mapTypes = null;
CloseableHttpClient client = HttpClients.createDefault();
// 2.使用get方法
HttpGet httpGet = new HttpGet(url);
CloseableHttpResponse response = null;
try {
// 3.執(zhí)行請求,獲取響應(yīng)
response = client.execute(httpGet);
// 4.獲取響應(yīng)的實體內(nèi)容
HttpEntity entity = response.getEntity();
if (entity != null) {
mapTypes = JSON.parseObject(EntityUtils.toString(entity, "utf-8"));
if (null != mapTypes.get("errmsg")) {
logger.info((String) mapTypes.get("errmsg"));
}
return mapTypes;
}
EntityUtils.consume(entity);
} catch (IOException e) {
// TODO Auto-generated catch block
logger.error("獲取信息失敗:" + e.getMessage());
} finally {
if (response != null) {
try {
response.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return null;
}
POST 請求:
/**
* * post請求
* * @param url
* * @param json
* * @return
*/
public JSONObject doPost(String url, JSONObject json) throws Exception{
DefaultHttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
JSONObject response = null;
String result = null;
try {
post.addHeader("Content-type","application/json; charset=utf-8");
post.setHeader("Accept", "application/json");
post.setEntity(new StringEntity(json.toString(), Charset.forName("UTF-8")));
HttpResponse res = client.execute(post);
if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
HttpEntity entity = res.getEntity();
result = EntityUtils.toString(res.getEntity());// 返回json格式:
response = JSONObject.parseObject(result);
}
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
client.close();
}
return response;
}
自己將服務(wù)封裝為 POST 請求:
/**
* 功能描述: 調(diào)用釘釘服務(wù)器接口,添加用戶信息
* @param: [request, name, mobile]
* @return: java.lang.String
* @auther: lsr
* @date: 2018/11/8 14:20
*/
@RequestMapping(value="/addUser",method= RequestMethod.POST)
private JSONObject addUser(@RequestBody(required=false) JSONObject jsonObject){
JSONObject resultObject = null;
if(jsonObject == null || jsonObject.equals(null)){
resultObject.put("errcode",9999);
resultObject.put("errmsg","調(diào)用釘釘服務(wù)器存在錯誤,用戶參數(shù)為空");
logger.error("調(diào)用釘釘服務(wù)器存在錯誤,用戶參數(shù)為空");
return resultObject;
}
JSONObject jsonParam = new JSONObject();
jsonParam.put("name", jsonObject.getString("name"));
jsonParam.put("mobile", jsonObject.getString("mobile"));
jsonParam.put("department", new int[]{1});
String accessToken = dingAuthHelpUtil.getAccessToken();
try {
resultObject = dingAuthHelpUtil.doPost("https://oapi.dingtalk.com/user/create?access_token=" + accessToken, jsonParam);
} catch (Exception e) {
logger.error(e.getMessage(),e);
logger.error("調(diào)用釘釘服務(wù)器失敗");
}
return resultObject;
}