使用httpclient模拟http请求其他系统的接口

目录

在javaee 工程趋向多模块化,低耦合的情况下,工程里面需要将越来越多的公共功能抽象出来,让多数人可以用,百度上能查到的都他妈的不完整,所以还不如自己去研究一下,一个get请求,一个post请求
get的url格式如下:

 token = https://api.weixin.qq.com/sns/oauth2/access_token?appid={app_id}&secret={app_secret}

导包

<properties> 
<commons-lang3.version>3.4</commons-lang3.version>
<httpclient.version>4.5.2</httpclient.version>
<httpmime.version>4.5.2</httpmime.version>
</properties>

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>${commons-lang3.version}</version>
</dependency>
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>${httpclient.version}</version>
</dependency>
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpmime</artifactId>
    <version>${httpmime.version}</version>
</dependency>

实现类

http请求一个get请求一个post请求
1.key 是 在配置文件中 配置的 url地址
2.urlaras是需要get方式传入的参数
3.postData是post请求时传入的参数

 public HttpResultBean componentPostJson(
            String key,
            Map<String, String> urlParas,
            Object postData) {
        String url = SysProperties.get(key);
        if(StringUtil.isNullOrBlank(url)){
            return null;
        }
        if(urlParas == null){
            urlParas = new HashMap<>();
        }
        url = RequestUtil.buildUrl(url, urlParas);
        String postDataStr = JSONUtil.getString(postData);
        HttpResultBean resultBean= HttpUtil.postJsonData(url, postDataStr);
        return resultBean;
    } 
    public HttpResultBean componentGetJson(String key, Map<String, String> urlParas, Object postData) {
        String url = SysProperties.get(key);
        if(StringUtil.isNullOrBlank(url)){
            return null;
        }
        if(urlParas == null){
            urlParas = new HashMap<>();
        }
        url = RequestUtil.buildUrl(url, urlParas);
        HttpResultBean resultBean= HttpUtil.getData(url);
        return resultBean;
    }

工具类

工具类基本上是所有工程都会用到的东西
1.SysProperties直接获取指定的配置文件中的key—value值

public class SysProperties {

    protected static Properties properties=null;

    static {
        properties=new Properties();
        InputStream in=SysProperties.class.getResourceAsStream("/dataAsyn.properties");
        try {
            properties.load(in);
        } catch (IOException e) {
        }
    }

    public static String get(String key){
        return properties.getProperty(key);
    }
}
  1. StringUtil 处理get请求中的url
    1. 首先引入 Common-lang3包中的 StringUtils
    2. get和post请求的格式
targetIndex=http://localhost:8080/eHR/targetIndex/getBonusTargetList 
web.oauth.access.token = https://api.weixin.qq.com/sns/oauth2/access_token?appid={app_id}&secret={app_secret}&code={code}&grant_type=authorization_code

对于url中的 ?id={app_id} 的处理

import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.Validate;
public class StringUtil extends StringUtils {

    public static String format(String format, Map<String, String> map) {
        String fieldStart = "\\{";
        String fieldEnd = "\\}";

        if (map == null) {
            return format;
        }
        String regex = fieldStart + "([^}]+)" + fieldEnd;
        Set<String> fields = getCustomField(format, fieldStart, fieldEnd);
        String result = format;
        for (String field: fields){
            String newVal = map.get(field);
            if(newVal == null){
                newVal = "";
            }
            result = result.replaceAll(fieldStart + field + fieldEnd, newVal);
        }
        return result;
    }
       public static Set<String> getCustomField(String format, String fieldStart, String fieldEnd) {

        Set<String> result = new HashSet<>();

        String regex = fieldStart + "([^}]+)" + fieldEnd;
        Pattern pattern = Pattern.compile(regex);
        Matcher m = pattern.matcher(format);
        while (m.find()) {
            result.add(m.group(1));
        }
        return result;
    }
    }

httpUtil的编写

package me.springboot.mybatis.util;

import ch.qos.logback.core.util.FileUtil;
import com.sun.deploy.net.HttpResponse;
import jdk.nashorn.api.scripting.JSObject;
import org.apache.http.*;
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.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils; 
public class HttpUtil  {
    /**
     * 获取GET 数据
     *
     * @param url
     * @return
     */
    public static HttpResultBean getData(String url) {

        return getData(url, "");
    }

    public static HttpResultBean getData(String url, String path) {

        CloseableHttpClient client = HttpClients.createDefault();
        HttpGet get = new HttpGet(url);
        CloseableHttpResponse response = null;
        HttpResultBean result = new HttpResultBean();
        try {
            response = client.execute(get);
            StatusLine status = response.getStatusLine();
            result.setStatus(status.getStatusCode());
            HttpEntity entity = response.getEntity();
            String content = EntityUtils.toString(entity, "UTF-8"); 
            result.setContent(content);
            result.setContentType(entity.getContentType().getValue());
            Header encodingHeader = entity.getContentEncoding();
            if (encodingHeader != null) {
                result.setContentEncoding(encodingHeader.getValue());
            }
            result.setContentLength(entity.getContentLength());
        } catch (IOException e) {
            return null;
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                }
            }
        }
        return result;
    }

    public static HttpResultBean postJsonData(String url, JSObject job) {
        String jsonStr = job.toString();
        return postJsonData(url, jsonStr);
    }

    public static HttpResultBean postJsonData(String url, String jsonStr) {

        CloseableHttpClient client = HttpClients.createDefault();
        HttpPost post = new HttpPost(url);
        CloseableHttpResponse response = null;
        HttpResultBean result = new HttpResultBean();
        try {
            StringEntity se = new StringEntity(jsonStr,
                    ContentType.create("application/json", "UTF-8"));
            post.setEntity(se);
            response = client.execute(post);
            StatusLine status = response.getStatusLine();
            result.setStatus(status.getStatusCode());
            HttpEntity entity = response.getEntity();
            String content = EntityUtils.toString(entity, "UTF-8");
            result.setContent(content);
            result.setContentType(entity.getContentType().getValue());
            Header encodingHeader = entity.getContentEncoding();
            if (encodingHeader != null) {
                result.setContentEncoding(encodingHeader.getValue());
            }
            result.setContentLength(entity.getContentLength());
        } catch (IOException e) {
            return null;
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                }
            }
        }
        return result;

    } 
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值