手把手教你在项目中传值给其它项目接口数据

项目中传值给其它项目接口数据

一个项目有时候需要和另外的项目数据互通,作为小白可能不知道如何处理,我将访问其它项目并传值的工具类放在了下面。

import com.sun.xml.internal.fastinfoset.Encoder;
import net.sf.json.JSONObject;
import org.apache.http.client.methods.*;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.jasig.cas.client.util.URIBuilder;

import java.io.IOException;
import java.net.URI;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class HttpClientUtil {

    /**
     * 带参数的get请求
     * @param url
     * @param param
     * @return String
     */
    public static String getApi(String url, Map<String, String> param) {
        // 创建Httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();
        String resultString = "";
        CloseableHttpResponse response = null;
        try {
            // 创建uri
            URIBuilder builder = new URIBuilder(url);
            if (param != null) {
                for (String key : param.keySet()) {
                    builder.addParameter(key, param.get(key));
                }
            }
            URI uri = builder.build();
            // 创建http GET请求
            HttpGet httpGet = new HttpGet(uri);
            // 执行请求
            response = httpclient.execute(httpGet);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                resultString = convertUnicodeToCh(EntityUtils.toString(response.getEntity(),"utf-8"));
                JSONObject jsonObject = JSONObject.fromObject(resultString);

                String data = jsonObject.getString("data");

            }else {
                System.out.println("发送GET请求出现异常!");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultString;
    }
    /**
     * 将unicode字符串转为正常字符串
     *
     * @param str unicode字符串(比如"\u67e5\u8be2\u6210\u529f")
     * @return 转换后的字符串(比如"查询成功")
     */
    private static String convertUnicodeToCh(String str) {
        Pattern pattern = Pattern.compile("(\\\\u(\\w{4}))");
        Matcher matcher = pattern.matcher(str);

        // 迭代,将str中的所有unicode转换为正常字符
        while (matcher.find()) {
            String unicodeFull = matcher.group(1); // 匹配出的每个字的unicode,比如\u67e5
            String unicodeNum = matcher.group(2); // 匹配出每个字的数字,比如\u67e5,会匹配出67e5

            // 将匹配出的数字按照16进制转换为10进制,转换为char类型,就是对应的正常字符了
            char singleChar = (char) Integer.parseInt(unicodeNum, 16);

            // 替换原始字符串中的unicode码
            str = str.replace(unicodeFull, singleChar + "");
        }
        return str;
    }


    /**
     * @param url  eg:http://localohost:8080/web/user
     * @param json eg:{"name":"aa","id":"1","password":"123"}
     * @return
     */
    public static String doPost(String url, String json) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String result = null;
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            // 创建请求内容
            StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
            httpPost.setEntity(entity);
            // 执行http请求
            response = httpClient.execute(httpPost);
            result = EntityUtils.toString(response.getEntity(), Encoder.UTF_8);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
            return result;
    }

    /**
     * @param url  eg:http://localohost:8080/web/user
     * @param json eg:{"name":"AA","id":"1"}
     * @return
     */
    public static String doPut(String url, String json) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String result = null;
        try {
            // 创建Http Post请求
            HttpPut httpPut = new HttpPut(url);
            // 创建请求内容
            StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
            httpPut.setEntity(entity);
            // 执行http请求
            response = httpClient.execute(httpPut);
            result = EntityUtils.toString(response.getEntity(), Encoder.UTF_8);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    /**
     * @param url eg:http://localohost:8080/web/user/1
     *            http://localohost:8080/web/user?id=1
     *            http://localohost:8080/web/user?id=1,2,3
     * @return
     */
    public static String doDelete(String url) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String result = null;
        try {
            // 创建Http Post请求
            HttpDelete httpDelete = new HttpDelete(url);
            // 执行http请求
            response = httpClient.execute(httpDelete);
            result = EntityUtils.toString(response.getEntity(), Encoder.UTF_8);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

}

注意是导入下面的这类些工具类在这里插入图片描述
pom文件需要引入下面三个工具包

        <dependency>
            <groupId>net.sf.json-lib</groupId>
            <artifactId>json-lib</artifactId>
            <version>2.4</version>
            <classifier>jdk15</classifier>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.24</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.12</version>
            <scope>compile</scope>
        </dependency>

需要在syncaddress.properties文件里面加入你需要访问的项目地址
在这里插入图片描述
最后在需要传值的时候调用该工具类中的相印方法

 try {
                    Properties properties = new Properties();
                    InputStream propertiesIn = DbService.class.getClassLoader().getResourceAsStream("syncaddress.properties");//文件名字
                    properties.load(propertiesIn);
                    //项目地址加上接口,完整的访问路劲
                    String url = properties.getProperty("zcglpath")+"/test";
                    doPost(url,jsonData);
                } catch (IOException e) {
                    e.printStackTrace();
                }
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值