SpringBoot使用httpclient發送Get,Post請求

 

SpringBoot版本爲2.0.1,pom文件添加依賴

        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.6</version>
        </dependency>

編寫HttpUtils工具類

import org.apache.commons.lang3.StringUtils;
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.client.utils.URIBuilder;
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 javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.URI;
import java.nio.charset.Charset;

/**
 * @author YoonaLt
 */
public class HttpUtils {
    /**
     * 發送 get 請求
     *
     * @param url 請求地址
     * @return 請求結果
     */
    public static String get(String url) {
        String result = null;
        CloseableHttpResponse response = null;
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            // 創建uri
            URIBuilder builder = new URIBuilder(url);
            URI uri = builder.build();
            // 創建http GET請求
            HttpGet httpGet = new HttpGet(uri);
            // 執行請求
            response = httpclient.execute(httpGet);
            if (response.getStatusLine().getStatusCode() == 200) {
                result = EntityUtils.toString(response.getEntity(), "UTF-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 發送 post 請求
     *
     * @param url     請求地址
     * @param jsonStr Form表單json字符串
     * @return 請求結果
     */
    public static String post(String url, String jsonStr) {
        // 創建httpClient
        CloseableHttpClient httpClient = HttpClients.createDefault();
        // 創建post請求方式實例
        HttpPost httpPost = new HttpPost(url);

        // 設置請求頭 發送的是json數據格式
        httpPost.setHeader("Content-type", "application/json;charset=utf-8");
        httpPost.setHeader("Connection", "Close");

        // 設置參數---設置消息實體 也就是攜帶的數據
        StringEntity entity = new StringEntity(jsonStr, Charset.forName("UTF-8"));
        // 設置編碼格式
        entity.setContentEncoding("UTF-8");
        // 發送Json格式的數據請求
        entity.setContentType("application/json");
        // 把請求消息實體塞進去
        httpPost.setEntity(entity);

        // 執行http的post請求
        CloseableHttpResponse httpResponse;
        String result = null;
        try {
            httpResponse = httpClient.execute(httpPost);
            result = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
        } catch (IOException e) {
            e.printStackTrace();
        }

        return result;
    }

    /**
     * 獲取請求ip地址
     */
    public static String getRequestIp(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (StringUtils.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)) {
            //多次反向代理後會有多個ip值,第一個ip纔是真實ip
            int index = ip.indexOf(",");
            if (index != -1) {
                return ip.substring(0, index);
            } else {
                return ip;
            }
        }
        ip = request.getHeader("X-Real-IP");
        if (StringUtils.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)) {
            return ip;
        }
        return request.getRemoteAddr();
    }
}

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章