zoukankan      html  css  js  c++  java
  • HttpClient接口调用-客户端

    import com.alibaba.fastjson.JSONObject;
    import lombok.extern.slf4j.Slf4j;
    import org.apache.commons.httpclient.HttpStatus;
    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.HttpClients;
    import org.apache.http.util.EntityUtils;
    
    import java.io.IOException;
    
    /**
     * @program: myt
     * @description
     * @author: wlv1314
     * @create: 2020-11-22 16:57
     **/
    @Slf4j
    public class HttpClientUtil {
    
        private static RequestConfig requestConfig=null;
        static {
            requestConfig = RequestConfig.custom().setConnectTimeout(1000).setSocketTimeout(3000).build();
        }
    
        /**
         * post请求传输json参数
         * @param url  url地址
         * @param jsonParam 参数
         * @return
         */
        public static JSONObject httpPost(String url, JSONObject jsonParam){
            // post请求返回结果
            CloseableHttpClient httpClient = HttpClients.createDefault();
            JSONObject jsonResult = null;
            HttpPost httpPost = new HttpPost(url);
            // 设置请求和传输超时时间
            httpPost.setConfig(requestConfig);
            try{
                if (null != jsonParam){
                    // 解决中文乱码问题
              //转为服务端编码格式
    StringEntity entity = new StringEntity(jsonParam.toString(), "GBK"); entity.setContentEncoding("GBK"); entity.setContentType("application/json"); httpPost.setEntity(entity); } CloseableHttpResponse result = httpClient.execute(httpPost); // 请求发送成功,并得到响应 if (result.getStatusLine().getStatusCode() == HttpStatus.SC_OK){ String str = ""; try{ // 读取服务器返回过来的json字符串数据 str = EntityUtils.toString(result.getEntity(), "utf-8"); // 把json字符串转换成json对象 jsonResult = JSONObject.parseObject(str); }catch (Exception e){ log.error("post请求提交失败:" + url, e); } } }catch (IOException e){ log.error("post请求提交失败:" + url, e); }finally{ httpPost.releaseConnection(); } return jsonResult; } }

    运行时报错:

    java.lang.ClassNotFoundException:org.apache.http.config.Lookup

    解决办法:

    大家在调用http接口是 需要的jar包是httpclient-4.5.jar,但是还需要httpcore-4.4.1.jar

    加入httpcore依赖即可。

  • 相关阅读:
    设计模式之一(策略模式)
    电脑开机进入不了XP界面
    IBM X系列笔记本通过U盘安装系统方法全攻略
    DELPHI 访问其它电脑文件(局域网)
    笔记本维修小插曲 屏幕不亮处理方式
    delphi 笔记
    电脑小子的新婚夜
    如何得到动态链接库的输出函数(delphi tdump.exe)
    sql server重复数据处理
    如何使用jQuery向asp.net Mvc传递复杂json数据Filter篇
  • 原文地址:https://www.cnblogs.com/wlv1314/p/14043360.html
Copyright © 2011-2022 走看看