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依赖即可。

 

posted @ 2020-11-26 17:18  wlv1314  阅读(506)  评论(0编辑  收藏  举报