Java 中 http調用接口demo

public <T> T post(String url, String accessToken, Map<String, String> param, RespCallback<T> callback)
      throws BusinessException {
   HttpPost httpPost = new HttpPost(url);
   //設置請求頭
   httpPost.setHeader("Cookie","client_token="+accessToken);
   
   List<NameValuePair> params = new ArrayList<>();
   param.forEach((name, value) -> {
      NameValuePair nameValuePair = new BasicNameValuePair(name, value);
      params.add(nameValuePair);
   });
   HttpEntity entity = new UrlEncodedFormEntity(params, StandardCharsets.UTF_8);
   httpPost.setEntity(entity);

   return this.send(httpPost, callback);
}

public <T> T send(HttpRequestBase request, RespCallback<T> callback) throws BusinessException {
   try {
      RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(10000)
            .setConnectionRequestTimeout(10000).setSocketTimeout(120000).build();
      request.setConfig(requestConfig);
      request.addHeader("Accept", "application/json");
      CloseableHttpResponse response = httpClient.execute(request);

      switch (response.getStatusLine().getStatusCode()) {
      case 200:
         String responseBody;

         try {
            HttpEntity httpEntity = response.getEntity();
            responseBody = EntityUtils.toString(httpEntity);
         } catch (ParseException | IOException e) {
            throw new BusinessException(ErrorEnum.ERROR_SYSTEM, e);
         }

         System.err.println(responseBody);
         T result = callback.callback(responseBody);
         return result;
      case 401:
         throw new BusinessException(ErrorEnum.AUTH_NO_AUTHORITY, "無權調用系統");
      default:
         throw new BusinessException(ErrorEnum.ERROR_SEND,"調用系統出錯");
      }
   } catch (BusinessException e) {
      throw e;
   } catch (Exception e) {
      LOGGER.error(e.getMessage(), e);
      throw new BusinessException(ErrorEnum.ERROR_SEND, "調用系統出錯");
   }
}

 

@Override
public JSONObject callback(String responseBody) throws BusinessException {
   JSONObject jsonObject = JSONObject.parseObject(responseBody);
   if (jsonObject.containsKey("flag")) {
      String flag = jsonObject.getString("flag");
      String code = jsonObject.getString("code");
      if(flag.equals("false") && !code.equals("666666")) {
         String errorInfo = "調用系統出錯:" + jsonObject.getString("message");
         LOGGER.error(errorInfo);
         throw new BusinessException(ErrorEnum.ERROR_SEND, errorInfo);
      }
   }

   return jsonObject;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章