使用http携带token请求第三方接口 并封装参数以post方式请求

2023-11-19

首先准备条件:
1:四个jar包:

fastjson-1.2.3.jar

commons-io-2.4.jar

commons-httpclient-3.1.jar

httpcore-4.3.jar

slf4j-api-1.7.7.jar //这个包有没有无所谓打日志的。最好有这样不用改代码不用把日志去掉

2:HttpClientUtil工具类


import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
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.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Map;

/**
 * Created by zcl on 2018/12/21.
 */
public class HttpClientUtil {
    private static final Logger logger = LoggerFactory.getLogger(HttpClientUtil.class);
    private static HttpClientUtil ins;
    private HttpClient httpClient;


    private HttpClientUtil() {
        httpClient = new HttpClient();

    }

    public static HttpClientUtil getInstance() {
        if (ins == null) {
            synchronized (HttpClientUtil.class) {
                ins = new HttpClientUtil();
            }
        }
        return ins;
    }


    /**
     * 下载文件
     *
     * @param fileUrl
     * @param filePath
     */
    public void downloadFile(String fileUrl, String filePath) {
        try {
            URL url = new URL(fileUrl);
            FileUtils.copyURLToFile(url, new File(filePath));
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取url内容
     *
     * @param url
     * @return
     */
    public String get(String url) {
        byte[] file = getByte(url);
        if (file != null) {
            return new String(file);
        }
        return "";
    }

    /**
     * 获取url返回的二进制形式
     *
     * @param url
     * @return
     */
    public byte[] getByte(String url) {
        GetMethod getMethod = new GetMethod(url);
        getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                new DefaultHttpMethodRetryHandler());
        getMethod.setRequestHeader("X-Requested-With", "XMLHttpRequest");
        getMethod.setRequestHeader("User-Agent", "Mozilla/5.0");
        synchronized (ins) {
            int statusCode = 0;
            try {
                statusCode = httpClient.executeMethod(getMethod);
                if (statusCode != HttpStatus.SC_OK) {
                    logger.error("Method failed: " + getMethod.getStatusLine());
                }
                return getMethod.getResponseBody();
            } catch (Exception e) {
                logger.error("https link error", e);
            } finally {
                getMethod.releaseConnection();
            }
        }
        return null;
    }

    /**
     * 只请求Get连接 不用返回
     *
     * @param url
     */
    public void sendGet(String url) {
        GetMethod getMethod = new GetMethod(url);
        getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                new DefaultHttpMethodRetryHandler());
        getMethod.setRequestHeader("X-Requested-With", "XMLHttpRequest");
        getMethod.setRequestHeader("User-Agent", "Mozilla/5.0");
        synchronized (ins) {
            try {
                httpClient.executeMethod(getMethod);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * get数据
     *
     * @param url
     * @return
     * @throws Exception
     */
    public String getRequest(String url) throws IllegalStateException, IOException {
        HttpClient client = new HttpClient();
        StringBuilder sb = new StringBuilder();
        InputStream ins = null;
        GetMethod method = new GetMethod(url);
        try {
            // Execute the method.
            int statusCode = client.executeMethod(method);
            if (statusCode == HttpStatus.SC_OK) {
                ins = method.getResponseBodyAsStream();
                byte[] b = new byte[1024];
                int r_len = 0;
                while ((r_len = ins.read(b)) > 0) {
                    sb.append(new String(b, 0, r_len, method
                            .getResponseCharSet()));
                }
            } else {
                logger.error("getRequest errorcode" + statusCode);
            }
        } catch (HttpException e) {
            logger.error("getRequest https link error", e);
        } catch (IOException e) {
            logger.error("getRequest https link error", e);
        } finally {
            method.releaseConnection();
            if (ins != null) {
                ins.close();
            }
        }
        return sb.toString();
    }

    /**
     * get数据,设置超时时间
     *
     * @param url
     * @return
     * @throws Exception
     */
    public String getRequestWithTimeout(String url) throws IllegalStateException, IOException {
        HttpClient client = new HttpClient();
        // 设置请求超时时间
        client.getHttpConnectionManager().getParams().setConnectionTimeout(2000);
        // 设置响应超时时间 
        client.getHttpConnectionManager().getParams().setSoTimeout(2000);

        StringBuilder sb = new StringBuilder();
        InputStream ins = null;
        GetMethod method = new GetMethod(url);
        try {
            // Execute the method.
            int statusCode = client.executeMethod(method);
            if (statusCode == HttpStatus.SC_OK) {
                ins = method.getResponseBodyAsStream();
                byte[] b = new byte[1024];
                int r_len = 0;
                while ((r_len = ins.read(b)) > 0) {
                    sb.append(new String(b, 0, r_len, "UTF-8"));
                }
            } else {
                logger.error("getRequestWithTimeout errorcode" + statusCode);
            }
        } catch (HttpException e) {
            logger.error("getRequestWithTimeout https link error, url=" + url, e);
        } catch (IOException e) {
            logger.error("getRequestWithTimeout https link error, url=" + url, e);
        } finally {
            method.releaseConnection();
            if (ins != null) {
                ins.close();
            }
        }
        return sb.toString();
    }

    /**
     * post数据
     *
     * @param url
     * @return
     * @throws Exception
     */
    public String postRequest(String url) throws IllegalStateException, IOException {
        HttpPost post = new HttpPost(url);
        RequestConfig requestConfig = RequestConfig.custom().setRelativeRedirectsAllowed(true).build();
        post.setConfig(requestConfig);

        String reUrl = "";

        try {
            // Execute the method.
            HttpResponse httpResponse = new DefaultHttpClient().execute(post);
            int statusCode = httpResponse.getStatusLine().getStatusCode();
            if (statusCode == HttpStatus.SC_MOVED_TEMPORARILY) {
                post.abort();//释放post请求
                reUrl = httpResponse.getLastHeader("Location").getValue();
            }
        } catch (HttpException e) {
            logger.error("Fatal protocol violation: " + e);
        } catch (IOException e) {
            logger.error("Fatal transport error: " + e);
        }
        return reUrl;
    }

    // 发送一个GET请求,参数形式key1=value1&key2=value2...
    public String post(String path, String params) {
        HttpURLConnection httpConn = null;
        BufferedReader in = null;
        PrintWriter out = null;
        try {
            URL url = new URL(path);
            httpConn = (HttpURLConnection) url.openConnection();
            httpConn.setRequestMethod("POST");
            httpConn.setDoInput(true);
            httpConn.setDoOutput(true);

            //发送post请求参数
            out = new PrintWriter(httpConn.getOutputStream());
            out.println(params);
            out.flush();

            //读取响应
            if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                StringBuffer content = new StringBuffer();
                String tempStr = "";
                in = new BufferedReader(new InputStreamReader(httpConn.getInputStream()));
                while ((tempStr = in.readLine()) != null) {
                    content.append(tempStr);
                }
                return content.toString();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                in.close();
                out.close();
                httpConn.disconnect();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 发送第三方广告请求
     *
     * @param url
     * @param params
     * @param appid
     * @param source
     * @return
     */
    public String sendAdHubpost(String url, String params, String appid, String source) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("RequestApp", appid);
            conn.setRequestProperty("RequestSource", source);
            conn.setRequestProperty("Content-Type", "application/json");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(params);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }

    /**
     * post请求,x-www-form-urlencoded 方式
     * @param url
     * @param params
     * @param
     * @return
     * @throws Exception
     */
    public  String post_urlencodeed(String url, String params) throws Exception {

        CloseableHttpClient httpclient = HttpClients.createDefault();

        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(2000).setConnectTimeout(2000).build();//设置请求和传输超时时间

        HttpPost httpPost = new HttpPost(url);// 创建httpPost

        httpPost.setConfig(requestConfig);

        httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
        String charSet = "UTF-8";
        StringEntity entity = new StringEntity(params, charSet);
        httpPost.setEntity(entity);
        CloseableHttpResponse response = null;

        try {

            response = httpclient.execute(httpPost);
            StatusLine status = response.getStatusLine();
            int state = status.getStatusCode();
            if (state == HttpStatus.SC_OK) {
                HttpEntity responseEntity = response.getEntity();
                String jsonString = EntityUtils.toString(responseEntity);
                return jsonString;
            }
            else{
                logger.error("请求返回:"+state+"("+url+")");
            }
        }
        finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 参数为json
     * @param url
     * @param jsonStr
     * @return
     * @throws IOException
     */
    public String postJson(String url, String jsonStr) throws IOException {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        StringEntity stringEntity = new StringEntity(jsonStr, "application/json", "utf-8");
        httpPost.setEntity(stringEntity);

        CloseableHttpResponse response = null;
        try {
            response = httpclient.execute(httpPost);
            HttpEntity resultEntity = response.getEntity();
            //System.out.println(entity1.getContentEncoding());
            InputStream inputStream = resultEntity.getContent();
            String content = IOUtils.toString(inputStream);
            EntityUtils.consume(resultEntity);//目的是关闭流
            return content;
        } finally {
            httpPost.releaseConnection();
            if (response != null)
                response.close();
        }

    }

    /**
     * 参数为json
     * @param url
     * @param header
     * @param jsonStr
     * @return
     * @throws IOException
     */
    public String postJson(String url, Map<String, String> header, String jsonStr) throws IOException {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        StringEntity stringEntity = new StringEntity(jsonStr, "application/json", "utf-8");
        httpPost.setEntity(stringEntity);
        
        // header
        for (Map.Entry<String, String> entry : header.entrySet()) {
        	httpPost.addHeader(entry.getKey(), entry.getValue());
        }

        CloseableHttpResponse response = null;
        try {
            response = httpclient.execute(httpPost);
            HttpEntity resultEntity = response.getEntity();
            InputStream inputStream = resultEntity.getContent();
            String content = IOUtils.toString(inputStream);
            EntityUtils.consume(resultEntity);//目的是关闭流
            return content;
        } finally {
            httpPost.releaseConnection();
            if (response != null)
                response.close();
        }
    }
}

3:代码案例测试:


import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.SymbolTable;
import com.youyuan.util.HttpClientUtil;
import org.junit.Test;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by YYBJ on 2019/2/27.
 *使用http携带token请求第三方接口 并封装参数以post方式请求
 * @author ZCL
 */
public class HttpDemo {
    public static void main(String[] args) {
        Token token = new Token();
        token.setToken("token123");
        token.setId(111);
        token.setTime(System.currentTimeMillis() / 1000);
        HttpDemo httpDemo = new HttpDemo();
        httpDemo.sendHttp(token);
    }

    public void sendHttp(Token token) {
        //换成你自己的路径
        String url="https://xxx/action/add?token=<TOKEN>&timestamp=<TIMESTAMP>";
        //url进行参数替换  这是第三方验证的必要参数
        url = url.replace("<TOKEN>", token.getToken()).
                replace("<TIMESTAMP>", token.getTime() + "");//时间是long类型替换参数需要String类型在long后加空字符变为String类型
        Map<String ,Object>  paramMap= new HashMap<>();
        paramMap.put("id", token.getId());
        paramMap.put("type", "login");
        paramMap.put("mobile_app_id", 123456);
        String jsonStr = JSONObject.toJSONString(paramMap);
        try {
            //发送请求并接受参数 一般返回json
            String httpRes = HttpClientUtil.getInstance().postJson(url, jsonStr);
            //将返回回来的字符串转换为json对象
            JSONObject jo = JSONObject.parseObject(httpRes);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    @Test
    public void action() throws IOException {
        String url = "https://xxx/user_actions/add?access_token=<ACCESS_TOKEN>&timestamp=<TIMESTAMP>&nonce=<NONCE>";
        url = url.replace("<ACCESS_TOKEN>", "token321").
                replace("<TIMESTAMP>", System.currentTimeMillis() / 1000 + "").
                replace("<NONCE>", System.currentTimeMillis() + "");

        String jsonParm = initUserActionParams(1314, "register", 2424);
        String resStr = HttpClientUtil.getInstance().postJson(url, jsonParm);
        JSONObject jo = JSONObject.parseObject(resStr);
        //后续操作返回的参数
    }

    private static String initUserActionParams( int AccountId, String Type, Integer dataSourceId){
        Action action = new Action();
        action.setUserId(136666666);
        action.setActionTime((int) (System.currentTimeMillis() / 1000));
        action.setActionType(Type);
        UserActionParam userActionParam = new UserActionParam();
        userActionParam.getActions().add(action);
        userActionParam.setAccountId(AccountId);
        userActionParam.setUser_action_id(dataSourceId);
        //将实例对象转化为json字符串
        return JSONObject.toJSONString(userActionParam);

    }

    public static class Token {
        private Integer id;
        private String token;
        private Long time;


        public Integer getId() {
            return id;
        }

        public void setId(Integer id) {
            this.id = id;
        }

        public String getToken() {
            return token;
        }

        public void setToken(String token) {
            this.token = token;
        }

        public Long getTime() {
            return time;
        }

        public void setTime(Long time) {
            this.time = time;
        }
    }

    public static class UserActionParam{
        int accountId;
        int user_action_id;//用户所创建的行为源id
        List<Action> actions = new ArrayList<>();

        public int getAccountId() {
            return accountId;
        }

        public void setAccountId(int accountId) {
            this.accountId = accountId;
        }

        public int getUser_action_id() {
            return user_action_id;
        }

        public void setUser_action_id(int user_action_id) {
            this.user_action_id = user_action_id;
        }

        public List<Action> getActions() {
            return actions;
        }

        public void setActions(List<Action> actions) {
            this.actions = actions;
        }
    }

}

到此httpclient案例结束,希望能对你有参考价值。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用http携带token请求第三方接口 并封装参数以post方式请求 的相关文章

随机推荐

  • 算法系列15天速成——第八天 线性表【下】

    一 线性表的简单回顾 上一篇跟大家聊过 线性表 顺序存储 通过实验 大家也知道 如果我每次向 顺序表的头部插入元素 都会引起痉挛 效率比较低下 第二点我们用顺序存储时 容 易受到长度的限制 反之就会造成空间资源的浪费 二 链表 对于顺序表存
  • Finetuner+:为企业实现大模型微调和私有化部署

    如 ChatGPT GPT4 这样的大型语言模型就像是你为公司请的一个牛人顾问 他在 OpenAI Google 等大公司被预训练了不少的行业内专业知识 所以加入你的公司后 你只需要输入 Prompt 给他 介绍一些业务上的背景知识 他就能
  • 2021-01-08

    问题 F 有序数组中插入元素 时间限制 1 Sec 内存限制 128 MB 提交 2116 解决 967 提交 状态 讨论版 题目描述 输入n n lt 20 输入n个有序整数 降序或升序 插入元素e 使新序列仍按原来的排序规则为有序序列
  • 【Java】Java中的String类

    文章目录 一 认识 String 类 二 String 类的常用方法 2 1 构造方法 2 2 String 类对象之间的比较 2 3 字符串查找 2 4 字符串的转换 2 5 字符串替换 2 6 字符串拆分 2 7 字符串截取 2 8 字
  • Java语言 ASCII to Hex 互转(IOT-示例)

    概述 最近想起之前做的IOT项目 使用JAVA写了一个
  • libcurl交叉编译支持https

    简介 libcurl是一个跨平台的网络协议库 支持dict file ftp ftps gopher http https imap imaps pop3 pop3s rtsp smb smbs smtp smtps telnet tftp
  • Android Ble 连接设备失败 onConnectionStateChange status 返回133

    Android Ble 连接设备失败时回调函数 onConnectionStateChange status 返回133 开始找问题 各种mac地址 权限 线程 找了个遍 结果就是返回纹丝不动 又因为 mBluetoothGatt mBlu
  • BUUCTF [极客大挑战 2019]Knife

    打开一看结合题目 就是连接一下菜刀蚁剑 菜刀没用过只有蚁剑 下面用蚁剑实现 设置好URL和链接密码 找到flag文件 打开后找到flag 文件上传漏洞 一句话木马 php Asp Aspx 前端判断文件后缀名可以Burp Suite配置好P
  • pygame小游戏之飞机拼音大作战( 送给娃学拼音的礼物,星际旅行)

    二娃再过一年就该上一年级了 但现阶段的拼音咋都学不进去 买了拼音挂图贴在墙上 拉都拉不到旁边 突发奇想 何不用python的pygame做个小游戏 在玩中也能学习 让学变得有趣 这对搞编程的来说小菜一碟 于是说干就干 两个晚上就成型啦 这里
  • 如何使用条件格式在Excel中突出显示行

    Conditional formatting lets you format cells in an Excel spreadsheet based on the cells content For example you could ha
  • 程序员在囧途之垃圾创业团队

    以前 空虚和寂寞 时写的一篇通过真实案例进行 小说化改编 文 原型中的 我 并不完全代表作者本人 特此拿出和大家分享 也与自己共勉 正文 这年头互联网创业有两个人就算一个团队了 如果是精英组成的团队往往两个人能抵得上十个人 但如果是一帮平庸
  • 接口测试postman和python代码实现

    postman是一个做接口测试的工具 它是谷歌公司的 可谓是根正苗红的大家族 在接口测试领域和它拼的一个手指头也能数得出来 POSTMAN本只是Chrome的一个插件工具 后来谷歌老爹看着小家伙越来越受测试工程师的喜爱 名气越来越大 便做了
  • 【Detectron2】入门03 Faster RCNN + VOC

    在detectron2 data datasets builtin py中可以看到在DatasetCatelog上各个数据集的注册 其中 root即为数据集的基地址 代码指明 root要么是DETECTRON2 DATASETS 要么是da
  • Beyond Compare使用和安装教程

    一 背景 Beyond Compare是一款文件和文件夹比较工具 它能够比较和同步文件夹和文件 并显示它们之间的差异 方便用户决定如何更新和管理它们 Beyond Compare的主要用途包括 文件和文件夹比较 用户可以将两个文件或文件夹进
  • 九种常见排序的比较和实现

    首先排序算法大的可以分为 关键字比较 非关键字比较 关键字比较 关键字比较就是通过关键字之间的比较和移动 从而使整个序列有序 而关键字比较的算法 又可以像下面这样划分 对于排序算法之间的比较 无异于时间复杂度和空间复杂度 看下面这张表格 由
  • OpenCV读取视频并获得相关属性信息

    使用VideoCapture读取视频 video cv2 VideoCapture r prototype mp4 通过下代码确定视频是否读取成功 is open video isOpened 读取成功后 通过VideoCapture ge
  • css实现响应式布局

    一 什么是响应式布局 响应式布局指的是同一页面在不同屏幕尺寸下有不同的布局 传统的开发方式是PC端开发一套 手机端再开发一套 而使用响应式布局只要开发一套就够了 响应式设计与自适应设计的区别 响应式开发一套界面 通过检测视口分辨率 针对不同
  • JQuery使用

    JQuery 框架 注意事项 在导入JQUREY外部文件的时候不可以使用自闭合标签 无效化导入且不报错 不可使用此方式加载 jQuery框架特点 免费开源 轻量级框架 占用资源少 运行速度快 宗旨 write less do more jQ
  • python下载安装教程(Python 3.10版本)

    目录 一 Python下载 二 Python安装 三 检查Python是否安装成功 今天换了新的电脑 需要重新安装python和PyCharm 就简单的写个教程吧 一 Python下载 1 进入Python官网 官网地址 https www
  • 使用http携带token请求第三方接口 并封装参数以post方式请求

    首先准备条件 1 四个jar包 fastjson 1 2 3 jar commons io 2 4 jar commons httpclient 3 1 jar httpcore 4 3 jar slf4j api 1 7 7 jar 这个