java 中接口调用

public String getSMSTemplate(Long id) {
        Properties prop = new Properties();
        String messageUrl="";
        URL settingsUrl =getClass().getClassLoader().getResource("/config/sysconfig/sysconfig.properties");
        try(InputStream in =settingsUrl.openStream();) {
            prop.load(in);
            messageUrl = prop.getProperty("message.url").trim();
            IOUtils.closeQuietly(in);
        } catch (Exception e) {

        }
        String url = messageUrl+"/txSns/template/findone";
        Map<String,String> params = new HashMap<>();
        params.put("modelId",String.valueOf(id));
        JSONObject json = JSONObject.parseObject(HttpUtil.doHttpPost(url,params));
        if (json.get("content")!=null) {
            return json.getString("content");
        }
        return "";
    }
String addSerial = HttpUtil.doHttpGet(getUrl()+"/txSns/tx/getAddSerial.do");

 

//获取配置文件中的接口地址
    private String getUrl() {
        Properties prop = new Properties();
        String messageUrl="";
        URL settingsUrl =getClass().getClassLoader().getResource("/config/sysconfig/sysconfig.properties");
        try(InputStream in =settingsUrl.openStream();) {
            prop.load(in);
            messageUrl = prop.getProperty("message.url").trim();
            IOUtils.closeQuietly(in);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return messageUrl;
    }

 

 

package com.ustc.base.common.util;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
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.StringEntity;
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 org.apache.log4j.Logger;
import net.minidev.json.JSONObject;

/**
 * 网络请求工具类
 * 
 */
public class HttpUtil {

    private static final Logger logger = Logger.getLogger(HttpUtil.class);
    private static final Integer SUCCESS = 200;
    private static final String UTF = "UTF-8";

    /**
     * Http Get 请求
     * 
     * @param requestUrl 请求地址
     * @return 服务器返回信息
     * @throws Exception
     */
    public static String doHttpGet(String requestUrl) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(requestUrl);
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(5000).setConnectTimeout(3000).build();// 设置响应超时时间和连接超时
        httpGet.setConfig(requestConfig);
        CloseableHttpResponse response = null;
        String result = null;
        try {
            response = httpClient.execute(httpGet);
            result = EntityUtils.toString(response.getEntity());

            if (response.getStatusLine().getStatusCode() == HttpUtil.SUCCESS) {// 请求成功
                return result;
            } else {// 请求失败
                throw new Exception("请求成功");
            }
        } catch (Exception e) {
            logger.error("系统异常", e);
            logger.error(result);
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    logger.error("系统异常", e);
                }
            }
        }

        return result;
    }

    /**
     * Http Get 请求
     * 
     * @param requestUrl 请求地址
     * @return 服务器返回信息
     * @throws Exception
     */
    public static String doHttpGet(String requestUrl, String sign, String appCode, String timestamp) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(requestUrl);
        httpGet.addHeader("sign", sign);
        httpGet.addHeader("appCode", appCode);
        httpGet.addHeader("timestamp", timestamp);
        CloseableHttpResponse response = null;
        String result = null;
        try {
            response = httpClient.execute(httpGet);
            result = EntityUtils.toString(response.getEntity());

            if (response.getStatusLine().getStatusCode() == HttpUtil.SUCCESS) {// 请求成功
                return result;
            } else {// 请求失败
                throw new Exception("请求成功");
            }
        } catch (Exception e) {
            logger.error("系统异常", e);
            logger.error(result);
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    logger.error("系统异常", e);
                }
            }
        }

        return result;
    }

    /**
     * Http Post 请求
     * 
     * @param requestUrl 请求地址
     * @param params     请求参数
     * @return 服务器返回信息
     */
    public static String doHttpPost(String requestUrl, Map<String, String> params) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(requestUrl);
        CloseableHttpResponse response = null;
        String result = null;
        try {
            // 设置请求参数
            if (params != null && !params.isEmpty()) {
                List<NameValuePair> pairList = new ArrayList<NameValuePair>();
                for (Entry<String, String> entry : params.entrySet()) {
                    pairList.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
                }
                httpPost.setEntity(new UrlEncodedFormEntity(pairList, HttpUtil.UTF));
            }
            response = httpClient.execute(httpPost);
            result = EntityUtils.toString(response.getEntity(), UTF);

            if (response.getStatusLine().getStatusCode() == HttpUtil.SUCCESS) {// 请求成功
                return result;
            } else {// 请求失败
                throw new Exception("请求失败");
            }
        } catch (Exception e) {
            logger.error("系统异常", e);
            logger.error(result);
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    logger.error("系统异常", e);
                }
            }
        }
        return result;
    }

    /**
     * @param requestUrl 请求地址
     * @param json       请求参数
     * @return 服务器返回信息
     */
    public static String doHttpPost(String requestUrl, JSONObject json) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(requestUrl);
        CloseableHttpResponse response = null;
        String result = null;

        try {
            // 设置请求参数
            if (json != null) {
                StringEntity entity = new StringEntity(json.toString(), UTF);
                entity.setContentEncoding(UTF);
                entity.setContentType("application/json");
                httpPost.setEntity(entity);
            }

            response = httpClient.execute(httpPost);
            result = EntityUtils.toString(response.getEntity(), UTF);

            if (response.getStatusLine().getStatusCode() == HttpUtil.SUCCESS) {// 请求成功
                return result;
            } else {// 请求失败
                throw new Exception("请求失败");
            }
        } catch (Exception e) {
            logger.error("系统异常", e);
            logger.error(result);
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    logger.error("系统异常", e);
                }
            }
        }

        return result;
    }

    
}

 

posted on 2021-07-28 15:03  ALWAYS☆REMIND  阅读(152)  评论(0编辑  收藏  举报

导航