【Java】+http


聲明:知識來源於 https://www.jb51.net/article/160395.htm

1、前言:

2、常用的2種方式

1、一種是通過HTTPClient這種第三方的開源框架去實現

2、一種是通過HttpURLConnection去實現,HttpURLConnection是JAVA的標准類,是JAVA比較原生的一種實現方式。(個人推薦)


 

2.1、方式1 HTTPClient:

package com.powerX.httpClient;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
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.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

public class HttpClient4 {

/** 請求方式1 : GET*/
  public static String doGet(String url) {
    CloseableHttpClient httpClient = null;
    CloseableHttpResponse response = null;
    String result = "";
    try {
      // 通過址默認配置創建一個httpClient實例
      httpClient = HttpClients.createDefault();
      // 創建httpGet遠程連接實例
      HttpGet httpGet = new HttpGet(url);
      // 設置請求頭信息,鑒權
      httpGet.setHeader("Authorization", "Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0");
      // 設置配置請求參數
      RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000)// 連接主機服務超時時間
          .setConnectionRequestTimeout(35000)// 請求超時時間
          .setSocketTimeout(60000)// 數據讀取超時時間
          .build();
      // 為httpGet實例設置配置
      httpGet.setConfig(requestConfig);
      // 執行get請求得到返回對象
      response = httpClient.execute(httpGet);
      // 通過返回對象獲取返回數據
      HttpEntity entity = response.getEntity();
      // 通過EntityUtils中的toString方法將結果轉換為字符串
      result = EntityUtils.toString(entity);
    } catch (ClientProtocolException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      // 關閉資源
      if (null != response) {
        try {
          response.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
      if (null != httpClient) {
        try {
          httpClient.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
    return result;
  }

/** 請求方式2 : POST*/
  public static String doPost(String url, Map<String, Object> paramMap) {
    CloseableHttpClient httpClient = null;
    CloseableHttpResponse httpResponse = null;
    String result = "";
    // 創建httpClient實例
    httpClient = HttpClients.createDefault();
    // 創建httpPost遠程連接實例
    HttpPost httpPost = new HttpPost(url);
    // 配置請求參數實例
    RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000)// 設置連接主機服務超時時間
        .setConnectionRequestTimeout(35000)// 設置連接請求超時時間
        .setSocketTimeout(60000)// 設置讀取數據連接超時時間
        .build();
    // 為httpPost實例設置配置
    httpPost.setConfig(requestConfig);
    // 設置請求頭
    httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
    // 封裝post請求參數
    if (null != paramMap && paramMap.size() > 0) {
      List<NameValuePair> nvps = new ArrayList<NameValuePair>();
      // 通過map集成entrySet方法獲取entity
      Set<Entry<String, Object>> entrySet = paramMap.entrySet();
      // 循環遍歷,獲取迭代器
      Iterator<Entry<String, Object>> iterator = entrySet.iterator();
      while (iterator.hasNext()) {
        Entry<String, Object> mapEntry = iterator.next();
        nvps.add(new BasicNameValuePair(mapEntry.getKey(), mapEntry.getValue().toString()));
      }

      // 為httpPost設置封裝好的請求參數
      try {
        httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
      } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
      }
    }
    try {
      // httpClient對象執行post請求,並返回響應參數對象
      httpResponse = httpClient.execute(httpPost);
      // 從響應對象中獲取響應內容
      HttpEntity entity = httpResponse.getEntity();
      result = EntityUtils.toString(entity);
    } catch (ClientProtocolException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      // 關閉資源
      if (null != httpResponse) {
        try {
          httpResponse.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
      if (null != httpClient) {
        try {
          httpClient.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
    return result;
  }
}

 

2.2、方式2 HttpURLConnection:

package com.powerX.httpClient;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class HttpClient {

/** 請求方式1 : GET*/
  public static String doGet(String httpurl) {
    HttpURLConnection connection = null;
    InputStream is = null;
    BufferedReader br = null;
    String result = null;// 返回結果字符串
    try {
      // 創建遠程url連接對象
      URL url = new URL(httpurl);
      // 通過遠程url連接對象打開一個連接,強轉成httpURLConnection類
      connection = (HttpURLConnection) url.openConnection();
      // 設置連接方式:get
      connection.setRequestMethod("GET");
      // 設置連接主機服務器的超時時間:15000毫秒
      connection.setConnectTimeout(15000);
      // 設置讀取遠程返回的數據時間:60000毫秒
      connection.setReadTimeout(60000);
      // 發送請求
      connection.connect();
      // 通過connection連接,獲取輸入流
      if (connection.getResponseCode() == 200) {
        is = connection.getInputStream();
        // 封裝輸入流is,並指定字符集
        br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
        // 存放數據
        StringBuffer sbf = new StringBuffer();
        String temp = null;
        while ((temp = br.readLine()) != null) {
          sbf.append(temp);
          sbf.append("\r\n");
        }
        result = sbf.toString();
      }
    } catch (MalformedURLException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      // 關閉資源
      if (null != br) {
        try {
          br.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }

      if (null != is) {
        try {
          is.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }

      connection.disconnect();// 關閉遠程連接
    }

    return result;
  }

/** 請求方式12: POST*/
  public static String doPost(String httpUrl, String param) {

    HttpURLConnection connection = null;
    InputStream is = null;
    OutputStream os = null;
    BufferedReader br = null;
    String result = null;
    try {
      URL url = new URL(httpUrl);
      // 通過遠程url連接對象打開連接
      connection = (HttpURLConnection) url.openConnection();
      // 設置連接請求方式
      connection.setRequestMethod("POST");
      // 設置連接主機服務器超時時間:15000毫秒
      connection.setConnectTimeout(15000);
      // 設置讀取主機服務器返回數據超時時間:60000毫秒
      connection.setReadTimeout(60000);

      // 默認值為:false,當向遠程服務器傳送數據/寫數據時,需要設置為true
      connection.setDoOutput(true);
      // 默認值為:true,當前向遠程服務讀取數據時,設置為true,該參數可有可無
      connection.setDoInput(true);
      // 設置傳入參數的格式:請求參數應該是 name1=value1&name2=value2 的形式。
      connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
      // 設置鑒權信息:Authorization: Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0
      connection.setRequestProperty("Authorization", "Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0");
      // 通過連接對象獲取一個輸出流
      os = connection.getOutputStream();
      // 通過輸出流對象將參數寫出去/傳輸出去,它是通過字節數組寫出的
      os.write(param.getBytes());
      // 通過連接對象獲取一個輸入流,向遠程讀取
      if (connection.getResponseCode() == 200) {

        is = connection.getInputStream();
        // 對輸入流對象進行包裝:charset根據工作項目組的要求來設置
        br = new BufferedReader(new InputStreamReader(is, "UTF-8"));

        StringBuffer sbf = new StringBuffer();
        String temp = null;
        // 循環遍歷一行一行讀取數據
        while ((temp = br.readLine()) != null) {
          sbf.append(temp);
          sbf.append("\r\n");
        }
        result = sbf.toString();
      }
    } catch (MalformedURLException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      // 關閉資源
      if (null != br) {
        try {
          br.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
      if (null != os) {
        try {
          os.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
      if (null != is) {
        try {
          is.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
      // 斷開與遠程地址url的連接
      connection.disconnect();
    }
    return result;
  }
}

 

3、封裝后

備注:可直接copy走使用

maven依賴:

        <!--            http 請求         -->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.3</version>
        </dependency>
        <!--        阿里巴巴處理JSON          -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.47</version>
        </dependency>

代碼:

package com.http;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.sql.SQLOutput;
import java.util.Map;

/**
 * @Author: Jarvis
 * @Date: 2020/5/12 15:56
 * @Version: v1.0.0
 * @Description: HttpURLConnection方式http請求(get、post)
 */

public class JHttpUtil {
    private static final String[] requestTypes = {"GET", "POST"};

    // 返回JSONObject格式
    public static JSONObject doGetReturnJSONObject(String httpUrl) {
        return baseRequestToJsonObject(requestTypes[0], httpUrl, null, null);
    }

    public static JSONObject doGetReturnJSONObject(String httpUrl, JSONObject params) {
        return baseRequestToJsonObject(requestTypes[0], httpUrl, null, params);
    }

    public static JSONObject doGetReturnJSONObject(String httpUrl, JSONObject params, JSONObject header) {
        return baseRequestToJsonObject(requestTypes[0], httpUrl, params, header);
    }

    public static JSONObject doPostReturnJSONObject(String httpUrl, JSONObject params) {
        return baseRequestToJsonObject(requestTypes[1], httpUrl, null, params);
    }

    public static JSONObject doGPostReturnJSONObject(String httpUrl, JSONObject params, JSONObject header) {
        return baseRequestToJsonObject(requestTypes[1], httpUrl, header, params);
    }

    // 返回JSONArray格式
    public static JSONArray doGetReturnJSONArray(String httpUrl) {
        return baseRequestToJsonArray(requestTypes[0], httpUrl, null, null);
    }

    public static JSONArray doGetReturnJSONArray(String httpUrl, JSONObject params) {
        return baseRequestToJsonArray(requestTypes[0], httpUrl, null, params);
    }

    public static JSONArray doGetReturnJSONArray(String httpUrl, JSONObject params, JSONObject header) {
        return baseRequestToJsonArray(requestTypes[0], httpUrl, params, header);
    }

    public static JSONArray doPostReturnJSONArray(String httpUrl, JSONObject params) {
        return baseRequestToJsonArray(requestTypes[1], httpUrl, null, params);
    }

    public static JSONArray doPostReturnJSONArray(String httpUrl, JSONObject params, JSONObject header) {
        return baseRequestToJsonArray(requestTypes[1], httpUrl, header, params);
    }

    // 返回String格式
    public static String doGetReturnString(String httpUrl) {
        return baseRequestToString(requestTypes[0], httpUrl, null, null);
    }

    public static String doGetReturnString(String httpUrl, JSONObject params) {
        return baseRequestToString(requestTypes[0], httpUrl, null, params);
    }

    public static String doGetReturnString(String httpUrl, JSONObject params, JSONObject header) {
        return baseRequestToString(requestTypes[0], httpUrl, params, header);
    }

    public static String doPostReturnString(String httpUrl, JSONObject params) {
        return baseRequestToString(requestTypes[1], httpUrl, null, params);
    }

    public static String doPostReturnString(String httpUrl, JSONObject params, JSONObject header) {
        return baseRequestToString(requestTypes[1], httpUrl, header, params);
    }

    private static JSONObject baseRequestToJsonObject(String requestType, String httpUrl, JSONObject header, JSONObject params) {
        String result = baseRequest(requestType, httpUrl, header, params);
        if (!result.startsWith("[{")) {
            return JSONObject.parseObject(result);
        }
        return null;
    }

    private static JSONArray baseRequestToJsonArray(String requestType, String httpUrl, JSONObject header, JSONObject params) {
        String result = baseRequest(requestType, httpUrl, header, params);
        if (result.startsWith("[{")) {
            return JSONArray.parseArray(result);
        }
        return null;
    }

    private static String baseRequestToString(String requestType, String httpUrl, JSONObject header, JSONObject params) {
        return baseRequest(requestType, httpUrl, header, params);
    }

    /**
     * 功能:請求配置基本方法
     *
     * @param requestType 請求類型(GET、POST 等等)
     * @param httpUrl     請求地址(純地址 不帶參數)
     * @param header      請求頭(JSON格式)
     * @param params      請求參數(JSON格式)
     * @return 返回請求后的數據(JSON格式)
     */
    private static String baseRequest(String requestType, String httpUrl, JSONObject header, JSONObject params) {
        HttpURLConnection connection = null;
        InputStream is = null;
        OutputStream os = null;
        BufferedReader br = null;
        String result = null;// 返回結果字符串
        long startTime = 0;
        long endTime = 0;
        long gapTime = 0;

        // GET請求 參數配置(參數拼接到url)
        if (params != null && requestType == requestTypes[0]) {
            httpUrl += "?";
            int i = 0;
            for (Map.Entry<String, Object> entry : params.entrySet()) {
                httpUrl += entry.getKey() + "=" + entry.getValue();
                // 若不是最后一個參數 則加“&”
                if (i < params.size() - 1) {
                    httpUrl += "&";
                }
                i++;
            }
        }

        try {
            // 創建遠程url連接對象
            URL url = new URL(httpUrl);
            // 通過遠程url連接對象打開一個連接,強轉成httpURLConnection類
            connection = (HttpURLConnection) url.openConnection();

            // 設置請求頭
            if (header != null) {
                for (Map.Entry<String, Object> entry : header.entrySet()) {
                    connection.setRequestProperty(entry.getKey(), String.valueOf(entry.getValue()));
                }
            }
            connection.setRequestMethod(requestType); // 設置連接方式
            connection.setConnectTimeout(5 * 60 * 1000); // 設置連接主機服務器的超時時間:5分鍾
            connection.setReadTimeout(5 * 60 * 1000); // 設置讀取遠程返回的數據時間:5分鍾

            // 為POST請求時 打開輸出流 並把參數傳輸出去
            if (requestType == requestTypes[1]) {
                connection.setDoOutput(true);
                // 通過連接對象獲取一個輸出流
                os = connection.getOutputStream();
                // 通過輸出流對象將參數寫出去/傳輸出去,它是通過字節數組寫出的
                os.write(params.toString().getBytes());
            }

            startTime = System.currentTimeMillis();
            connection.connect(); // 發送請求

            // 通過connection連接 獲取輸入流
            if (200 == connection.getResponseCode()) {
                is = connection.getInputStream();
                // 封裝輸入流is,並指定字符集
                br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                // 存放數據
                StringBuffer sbf = new StringBuffer();
                String temp = null;
                while ((temp = br.readLine()) != null) {
                    sbf.append(temp);
                    sbf.append("\r\n");
                }
                result = sbf.toString();
            }
            endTime = System.currentTimeMillis();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 關閉資源
            if (null != br) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            connection.disconnect();// 關閉遠程連接
        }
        gapTime = endTime - startTime;
        String resultJson = result;

        // 做個開關 是否打印請求及響應信息(供擴展)
        boolean isPrintRequestAndResponseData = true;
        if (isPrintRequestAndResponseData) {
            // 打印請求頭
            System.out.println("******************** 請求響應數據 **********************");
            System.out.println(String.format("【請求耗時】:\n%sms", gapTime));
            System.out.println(String.format("【請求頭】:\n%s", header));
            // 打印請求地址
            System.out.println(String.format("【請求地址】(%s):\n%s", requestType, httpUrl));
            // 打印請求數據(非GET)
            if (!requestType.equals(requestTypes[0])) {
                System.out.println(String.format("【請求參數】:\n%s", JSON.toJSONString(
                        params,
                        SerializerFeature.PrettyFormat,
                        SerializerFeature.WriteMapNullValue,
                        SerializerFeature.WriteDateUseDateFormat)));
            }
            // 打印響應數據(若返回數據長度大於10000 則截取前50后50)
            // 做個開關 是否截取(供以后擴展)
            boolean isCutResponse = true;
            if (isCutResponse && resultJson.length() >= 10000) {
                String frist = resultJson.substring(0, 50);
                String last = resultJson.substring(resultJson.length() - 50, resultJson.length());
                System.out.println(String.format("【返回數據】:\n%s", frist + "......返回數據長度大於10000 僅顯示前50后50位......" + last));
            } else {
                System.out.println(String.format("【返回數據】:\n%s", JSON.toJSONString(
                        resultJson,
                        SerializerFeature.PrettyFormat,
                        SerializerFeature.WriteMapNullValue,
                        SerializerFeature.WriteDateUseDateFormat)));
            }
            System.out.println("*******************************************************\r\n");
        }

        return resultJson;
    }
}

 


免責聲明!

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



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