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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM