【httpclient-4.3.1.jar】httpclient發送get、post請求以及攜帶數據上傳文件


 

工具類封裝如下:

package cn.qlq.utils;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
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.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * http工具類的使用
 * 
 * @author Administrator
 *
 */
public class HttpUtils {

    private static Logger logger = LoggerFactory.getLogger(HttpUtils.class);

    /**
     * get請求
     * 
     * @return
     */
    public static String doGet(String url) {
        CloseableHttpClient client = null;
        CloseableHttpResponse response = null;
        try {
            // 定義HttpClient
            client = HttpClientBuilder.create().build();
            // 發送get請求
            HttpGet request = new HttpGet(url);
            // 執行請求
            response = client.execute(request);

            return getResponseResult(response);
        } catch (Exception e) {
            logger.error("execute error,url: {}", url, e);
        } finally {
            IOUtils.closeQuietly(response);
            IOUtils.closeQuietly(client);
        }

        return "";
    }

    /**
     * get請求攜帶參數
     * 
     * @return
     */
    public static String doGetWithParams(String url, Map<String, String> params) {
        CloseableHttpClient client = null;
        CloseableHttpResponse response = null;
        try {
            // 定義HttpClient
            client = HttpClientBuilder.create().build();

            // 1.轉化參數
            if (params != null && params.size() > 0) {
                List<NameValuePair> nvps = new ArrayList<NameValuePair>();
                for (Iterator<String> iter = params.keySet().iterator(); iter.hasNext();) {
                    String name = iter.next();
                    String value = params.get(name);
                    nvps.add(new BasicNameValuePair(name, value));
                }
                String paramsStr = EntityUtils.toString(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
                url += "?" + paramsStr;
            }

            HttpGet request = new HttpGet(url);
            response = client.execute(request);

            return getResponseResult(response);
        } catch (IOException e) {
            logger.error("execute error,url: {}", url, e);
        } finally {
            IOUtils.closeQuietly(response);
            IOUtils.closeQuietly(client);
        }

        return "";
    }

    public static String doPost(String url, Map<String, String> params) {
        CloseableHttpClient client = null;
        CloseableHttpResponse response = null;
        try {
            // 定義HttpClient
            client = HttpClientBuilder.create().build();
            HttpPost request = new HttpPost(url);

            // 1.轉化參數
            if (params != null && params.size() > 0) {
                List<NameValuePair> nvps = new ArrayList<NameValuePair>();
                for (Iterator<String> iter = params.keySet().iterator(); iter.hasNext();) {
                    String name = iter.next();
                    String value = params.get(name);
                    nvps.add(new BasicNameValuePair(name, value));
                }
                request.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
            }

            response = client.execute(request);
            return getResponseResult(response);
        } catch (IOException e) {
            logger.error("execute error,url: {}", url, e);
        } finally {
            IOUtils.closeQuietly(response);
            IOUtils.closeQuietly(client);
        }

        return "";
    }

    public static String doPost(String url, String params) {
        return doPost(url, params, false);
    }

    /**
     * post請求(用於請求json格式的參數)
     * 
     * @param url
     * @param params
     * @param isJsonData
     * @return
     */
    public static String doPost(String url, String params, boolean isJsonData) {
        CloseableHttpClient client = null;
        CloseableHttpResponse response = null;
        try {
            // 定義HttpClient
            client = HttpClientBuilder.create().build();

            HttpPost request = new HttpPost(url);
            StringEntity entity = new StringEntity(params, HTTP.UTF_8);
            request.setEntity(entity);

            if (isJsonData) {
                request.setHeader("Accept", "application/json");
                request.setHeader("Content-Type", "application/json");
            }

            response = client.execute(request);

            return getResponseResult(response);
        } catch (IOException e) {
            logger.error("execute error,url: {}", url, e);
        } finally {
            IOUtils.closeQuietly(response);
            IOUtils.closeQuietly(client);
        }

        return "";
    }

    /**
     * 上傳文件攜帶參數發送請求
     * 
     * @param url
     *            URL
     * @param fileName
     *            neme,相當於input的name
     * @param filePath
     *            本地路徑
     * @param params
     *            參數
     * @return
     */
    public static String doPostWithFile(String url, String fileName, String filePath, Map<String, String> params) {
        CloseableHttpClient httpclient = HttpClientBuilder.create().build();
        CloseableHttpResponse response = null;
        try {
            MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();

            // 上傳文件,如果不需要上傳文件注掉此行
            multipartEntityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE).addPart(fileName,
                    new FileBody(new File(filePath)));

            if (params != null && params.size() > 0) {
                Set<Entry<String, String>> entrySet = params.entrySet();
                for (Entry<String, String> entry : entrySet) {
                    multipartEntityBuilder.addTextBody(entry.getKey(), entry.getValue(),
                            ContentType.create(HTTP.PLAIN_TEXT_TYPE, StandardCharsets.UTF_8));
                }
            }

            HttpEntity httpEntity = multipartEntityBuilder.build();

            HttpPost httppost = new HttpPost(url);
            httppost.setEntity(httpEntity);

            response = httpclient.execute(httppost);
            return getResponseResult(response);
        } catch (Exception e) {
            logger.error("execute error,url: {}", url, e);
        } finally {
            IOUtils.closeQuietly(response);
            IOUtils.closeQuietly(httpclient);
        }

        return "";
    }

    private static String getResponseResult(CloseableHttpResponse response) throws ParseException, IOException {
        /** 請求發送成功,並得到響應 **/
        if (response != null) {
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                return EntityUtils.toString(response.getEntity(), "utf-8");
            } else {
                logger.error("getResponseResult code error, code: {}", response.getStatusLine().getStatusCode());
            }
        }

        return "";
    }
}

  上述代碼支持application/json數據的傳送。post方法的isJsonData 為true即在請求頭部加上application/json。

 

測試代碼:

Controller層:

    @RequestMapping("/test")
    @ResponseBody
    public String test(HttpServletRequest request, HttpServletResponse response) {
        String method = request.getMethod();
        System.out.println("========================");
        System.out.println("request.getMethod(): " + method);

        Enumeration<String> parameterNames = request.getParameterNames();
        while (parameterNames.hasMoreElements()) {
            String parameterName = (String) parameterNames.nextElement();
            String parameterValue = request.getParameter(parameterName);
            System.out.println("  parameterName: " + parameterName + " , parameterValue: " + parameterValue + " ");
        }

        return "success";
    }

 

測試:

    public static void main(String[] args) {
        String doGet = doGet("http://localhost:8088//weixin/test/test.html?name=zs&age=25");
        System.out.println(doGet);

        Map<String, String> map = new HashMap<String, String>();
        map.put("xx", "xxx");
        String doGetWithParams = doGetWithParams("http://localhost:8088//weixin/test/test.html", map);
        System.out.println(doGetWithParams);

        String doPost = doPost("http://localhost:8088//weixin/test/test.html?name=zs&age=25", "");
        System.out.println(doPost);

        String doPost2 = doPost("http://localhost:8088//weixin/test/test.html?name=zs&age=25", map);
        System.out.println(doPost2);
    }

結果:

========================
request.getMethod(): GET
parameterName: name , parameterValue: zs
parameterName: age , parameterValue: 25
========================
request.getMethod(): GET
parameterName: xx , parameterValue: xxx
========================
request.getMethod(): POST
parameterName: name , parameterValue: zs
parameterName: age , parameterValue: 25
========================
request.getMethod(): POST
parameterName: name , parameterValue: zs
parameterName: age , parameterValue: 25
parameterName: xx , parameterValue: xxx

 

補充:NameValuePair是鍵值對的數據結構,內部維護一個key屬性、一個value屬性。有時候可替代map解決一些問題:

public interface NameValuePair {

    String getName();

    String getValue();

}

例如:

        Map<String, String> params = new HashMap<>();
        params.put("name", "zhangsan");
        params.put("age", "25");
        params.put("sex", "男");
        params.put("network", "http://zhangsan.com");

        List<NameValuePair> nameValuePairs = new LinkedList<>();
        for (Iterator<Entry<String, String>> iterator = params.entrySet().iterator(); iterator.hasNext();) {
            Entry<String, String> next = iterator.next();
            String key = next.getKey();
            String value = next.getValue();
            nameValuePairs.add(new BasicNameValuePair(key, value));
        }
        String string = EntityUtils.toString(new UrlEncodedFormEntity(nameValuePairs));
        System.out.println(string);

        // URLEncodedUtils工具類使用
        System.out.println("========URLEncodedUtils編碼解碼======");
        String format = URLEncodedUtils.format(nameValuePairs, StandardCharsets.UTF_8);
        System.out.println(format);

        List<NameValuePair> parse = URLEncodedUtils.parse(format, StandardCharsets.UTF_8);
        System.out.println(parse);

結果:

sex=%3F&age=25&name=zhangsan&network=http%3A%2F%2Fzhangsan.com
========URLEncodedUtils編碼解碼======
sex=%E7%94%B7&age=25&name=zhangsan&network=http%3A%2F%2Fzhangsan.com
[sex=男, age=25, name=zhangsan, network=http://zhangsan.com]

 


免責聲明!

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



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