Java工具類HttpUtil


1.依賴

<!--HttpClient-->
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.12</version>
</dependency>

2.代碼

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
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 java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Map;

public class HttpUtil {
    /**
     * HttpClient send Post
     */
    public byte[] httpClientPost(final String url,final List<NameValuePair> params){
        // 客戶端實例
        CloseableHttpClient httpClient = HttpClients.createDefault();
        // post實例
        HttpPost httpPost = new HttpPost(url);
        // 返回請求
        CloseableHttpResponse response = null;
        // IO流
        InputStream inputStream = null;
        try {
            // 參數設置
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params);
            entity.setContentType("application/json;charset=utf-8");
            httpPost.setEntity(entity);
            httpPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; rv:6.0.2) Gecko/20100101 Firefox/6.0.2");
            // 返回請求
            response = httpClient.execute(httpPost);
            // 獲取響應碼
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != 200) {
                System.out.println("響應編碼:" + response.getStatusLine().getStatusCode());
                System.out.println("請求失敗:" + response.getStatusLine().getReasonPhrase());
            } else {
                System.out.println("響應編碼:" + response.getStatusLine().getStatusCode());
                System.out.println("請求成功:" + response.getStatusLine().getReasonPhrase());
                // 獲取全部的請求頭
                Header[] headers = response.getAllHeaders();
                for (int i = 0; i < headers.length; i++) {
                    System.out.println("全部的請求頭:" + headers[i]);
                }
                // 獲取響應消息實體
                HttpEntity httpEntity = response.getEntity();
                // 返回IO流
                inputStream = httpEntity.getContent();
                // 返回bytes
                byte[] buffer = new byte[1024];
                int len = 0;
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                while ((len = inputStream.read(buffer)) != -1) {
                    bos.write(buffer, 0, len);
                }
                bos.close();
                // 返回響應內容
                return bos.toByteArray();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 關閉inputStream和httpResponse
            if (inputStream != null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (response != null){
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
        return null;
    }
    /**
     * HttpClient send Get
     */
    public byte[] httpClientGet(final String url){
        // 客戶端實例
        CloseableHttpClient httpClient = HttpClients.createDefault();
        // post實例
        HttpGet httpGet = new HttpGet(url);
        // 返回請求
        CloseableHttpResponse response = null;
        // IO流
        InputStream inputStream = null;
        try {
            // 參數設置
            httpGet.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; rv:6.0.2) Gecko/20100101 Firefox/6.0.2");
            // 返回請求
            response = httpClient.execute(httpGet);
            // 獲取響應碼
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != 200) {
                System.out.println("響應編碼:" + response.getStatusLine().getStatusCode());
                System.out.println("請求失敗:" + response.getStatusLine().getReasonPhrase());
            } else {
                System.out.println("響應編碼:" + response.getStatusLine().getStatusCode());
                System.out.println("請求成功:" + response.getStatusLine().getReasonPhrase());
                // 獲取全部的請求頭
                Header[] headers = response.getAllHeaders();
                for (int i = 0; i < headers.length; i++) {
                    System.out.println(headers[i]);
                }
                // 獲取響應消息實體
                HttpEntity httpEntity = response.getEntity();
                // 返回IO流
                inputStream = httpEntity.getContent();
                // 返回bytes
                byte[] buffer = new byte[1024];
                int len = 0;
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                while ((len = inputStream.read(buffer)) != -1) {
                    bos.write(buffer, 0, len);
                }
                bos.close();
                // 返回響應內容
                return bos.toByteArray();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 關閉inputStream和httpResponse
            if (inputStream != null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (response != null){
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
        return null;
    }
    /**
     * HttpURLConnection send Post
     */
    public byte[] httpPost(final String uri,final String params){
        HttpURLConnection connection = null;
        InputStream inputStream = null;
        try {
            URL url = new URL(uri);
            connection = (HttpURLConnection) url.openConnection();
            // 讀取超時
            connection.setReadTimeout(5000);
            // 連接超時
            connection.setConnectTimeout(5000);
            // 緩存
            connection.setUseCaches(false);
            // 發送方式
            connection.setRequestMethod("POST");
            // 允許輸入輸出
            connection.setDoOutput(true);
            connection.setDoInput(true);
            // 設置headers
            connection.setRequestProperty("Content-Type","application/json;charset=utf-8");
            connection.setRequestProperty("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.102 Safari/537.36");
            // 參數設置
            OutputStream outputStream = connection.getOutputStream();
            outputStream.write(params.getBytes("UTF-8"));
            outputStream.flush();
            outputStream.close();
            // 返回碼
            int responseCode = connection.getResponseCode();
            if(responseCode != 200){
                System.out.println("請求失敗:" + connection.getResponseMessage());
                System.out.println("響應編碼:" + connection.getResponseCode());
                return null;
            }else{
                System.out.println("請求成功:" + connection.getResponseMessage());
                System.out.println("響應編碼:" + connection.getResponseCode());
                // 返回headers
                Map<String, List<String>> map = connection.getHeaderFields();
                System.out.println(map.toString());
                // 返回流
                inputStream = connection.getInputStream();
                // 返回bytes
                byte[] buffer = new byte[1024];
                int len = 0;
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                while ((len = inputStream.read(buffer)) != -1) {
                    bos.write(buffer, 0, len);
                }
                bos.close();
                // 返回響應內容
                return bos.toByteArray();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 關閉inputStream和httpResponse
            if (inputStream != null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (connection != null){
                connection.disconnect();
            }
        }
        return null;
    }
    /**
     * HttpURlConnection send Get
     */
    public byte[] httpGet(final String uri){
        HttpURLConnection connection = null;
        InputStream inputStream = null;
        try {
            URL url = new URL(uri);
            connection = (HttpURLConnection) url.openConnection();
            // 讀取超時
            connection.setReadTimeout(5000);
            // 連接超時
            connection.setConnectTimeout(5000);
            // 緩存
            connection.setUseCaches(false);
            // 發送方式
            connection.setRequestMethod("GET");
            // 設置headers
            connection.setRequestProperty("Content-Type","application/json;charset=utf-8");
            connection.setRequestProperty("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.102 Safari/537.36");
            // 返回碼
            int responseCode = connection.getResponseCode();
            if(responseCode != 200){
                System.out.println("請求失敗:" + connection.getResponseMessage());
                System.out.println("響應編碼:" + connection.getResponseCode());
                return null;
            }else{
                System.out.println("請求成功:" + connection.getResponseMessage());
                System.out.println("響應編碼:" + connection.getResponseCode());
                // 返回headers
                Map<String, List<String>> map = connection.getHeaderFields();
                System.out.println(map.toString());
                // 返回流
                inputStream = connection.getInputStream();
                // 返回bytes
                byte[] buffer = new byte[1024];
                int len = 0;
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                while ((len = inputStream.read(buffer)) != -1) {
                    bos.write(buffer, 0, len);
                }
                bos.close();
                // 返回響應內容
                return bos.toByteArray();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 關閉inputStream和httpResponse
            if (inputStream != null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (connection != null){
                connection.disconnect();
            }
        }
        return null;
    }

    public static void main(String[] args) {
        String url = "http://img1.juimg.com/181219/330479-1Q2191H04958.jpg";
        //byte[] bytes = new HttpUtil().httpClientGet(url);
        byte[] bytes = new HttpUtil().httpGet(url);
        System.out.println(bytes.length);
    }
}

 


免責聲明!

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



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