1. 程式人生 > >使用HttpClient 傳送 GET、POST、PUT、Delete請求及檔案上傳

使用HttpClient 傳送 GET、POST、PUT、Delete請求及檔案上傳

  
import java.io.File;  
import java.io.IOException;    
import java.io.UnsupportedEncodingException;    
import java.nio.charset.Charset;  
import java.util.ArrayList;    
import java.util.List;    
import java.util.Map;    
import java.util.Set;    
  
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.HttpDelete;  
import org.apache.http.client.methods.HttpGet;    
import org.apache.http.client.methods.HttpPost;    
import org.apache.http.client.methods.HttpPut;  
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.impl.client.CloseableHttpClient;    
import org.apache.http.impl.client.HttpClientBuilder;    
import org.apache.http.impl.client.HttpClients;    
import org.apache.http.message.BasicNameValuePair;    
import org.apache.http.util.EntityUtils;    
import org.caeit.cloud.dev.entity.HttpResponse;  
    
public class HttpClientUtil {    
        
    /**  
     * 傳送http get請求  
     */    
    public static HttpResponse httpGet(String url,Map<String,String> headers,String encode){    
        HttpResponse response = new HttpResponse();  
        if(encode == null){    
            encode = "utf-8";    
        }    
        String content = null;    
        //since 4.3 不再使用 DefaultHttpClient    
        CloseableHttpClient closeableHttpClient = HttpClientBuilder.create().build();     
        HttpGet httpGet = new HttpGet(url);    
        //設定header  
        if (headers != null && headers.size() > 0) {  
            for (Map.Entry<String, String> entry : headers.entrySet()) {  
                httpGet.setHeader(entry.getKey(),entry.getValue());  
            }  
        }  
        CloseableHttpResponse httpResponse = null;    
        try {    
            httpResponse = closeableHttpClient.execute(httpGet);    
            HttpEntity entity = httpResponse.getEntity();    
            content = EntityUtils.toString(entity, encode);    
            response.setBody(content);  
            response.setHeaders(httpResponse.getAllHeaders());  
            response.setReasonPhrase(httpResponse.getStatusLine().getReasonPhrase());  
            response.setStatusCode(httpResponse.getStatusLine().getStatusCode());  
        } catch (Exception e) {    
            e.printStackTrace();    
        }finally{    
            try {    
                httpResponse.close();    
            } catch (IOException e) {    
                e.printStackTrace();    
            }    
        }    
        try {  //關閉連線、釋放資源    
            closeableHttpClient.close();    
        } catch (IOException e) {    
            e.printStackTrace();    
        }      
        return response;    
    }    
    /**  
     * 傳送 http post 請求,引數以form表單鍵值對的形式提交。  
     */    
    public static HttpResponse httpPostForm(String url,Map<String,String> params, Map<String,String> headers,String encode){    
        HttpResponse response = new HttpResponse();  
        if(encode == null){    
            encode = "utf-8";    
        }    
        //HttpClients.createDefault()等價於 HttpClientBuilder.create().build();     
        CloseableHttpClient closeableHttpClient = HttpClients.createDefault();     
        HttpPost httpost = new HttpPost(url);    
          
        //設定header  
        if (headers != null && headers.size() > 0) {  
            for (Map.Entry<String, String> entry : headers.entrySet()) {  
                httpost.setHeader(entry.getKey(),entry.getValue());  
            }  
        }  
        //組織請求引數    
        List<NameValuePair> paramList = new ArrayList <NameValuePair>();    
        if(params != null && params.size() > 0){  
            Set<String> keySet = params.keySet();    
            for(String key : keySet) {    
                paramList.add(new BasicNameValuePair(key, params.get(key)));    
            }    
        }  
        try {    
            httpost.setEntity(new UrlEncodedFormEntity(paramList, encode));    
        } catch (UnsupportedEncodingException e1) {    
            e1.printStackTrace();    
        }    
        String content = null;    
        CloseableHttpResponse  httpResponse = null;    
        try {    
            httpResponse = closeableHttpClient.execute(httpost);    
            HttpEntity entity = httpResponse.getEntity();    
            content = EntityUtils.toString(entity, encode);    
            response.setBody(content);  
            response.setHeaders(httpResponse.getAllHeaders());  
            response.setReasonPhrase(httpResponse.getStatusLine().getReasonPhrase());  
            response.setStatusCode(httpResponse.getStatusLine().getStatusCode());  
        } catch (Exception e) {    
            e.printStackTrace();    
        }finally{    
            try {    
                httpResponse.close();    
            } catch (IOException e) {    
                e.printStackTrace();    
            }    
        }    
        try {  //關閉連線、釋放資源    
            closeableHttpClient.close();    
        } catch (IOException e) {    
            e.printStackTrace();    
        }      
        return response;    
    }    
        
    /**  
     * 傳送 http post 請求,引數以原生字串進行提交  
     * @param url  
     * @param encode  
     * @return  
     */    
    public static HttpResponse httpPostRaw(String url,String stringJson,Map<String,String> headers, String encode){    
        HttpResponse response = new HttpResponse();  
        if(encode == null){    
            encode = "utf-8";    
        }    
        //HttpClients.createDefault()等價於 HttpClientBuilder.create().build();     
        CloseableHttpClient closeableHttpClient = HttpClients.createDefault();     
        HttpPost httpost = new HttpPost(url);    
          
        //設定header  
        httpost.setHeader("Content-type", "application/json");      
        if (headers != null && headers.size() > 0) {  
            for (Map.Entry<String, String> entry : headers.entrySet()) {  
                httpost.setHeader(entry.getKey(),entry.getValue());  
            }  
        }  
        //組織請求引數    
        StringEntity stringEntity = new StringEntity(stringJson, encode);    
        httpost.setEntity(stringEntity);    
        String content = null;    
        CloseableHttpResponse  httpResponse = null;    
        try {    
            //響應資訊  
            httpResponse = closeableHttpClient.execute(httpost);    
            HttpEntity entity = httpResponse.getEntity();    
            content = EntityUtils.toString(entity, encode);    
            response.setBody(content);  
            response.setHeaders(httpResponse.getAllHeaders());  
            response.setReasonPhrase(httpResponse.getStatusLine().getReasonPhrase());  
            response.setStatusCode(httpResponse.getStatusLine().getStatusCode());  
        } catch (Exception e) {    
            e.printStackTrace();    
        }finally{    
            try {    
                httpResponse.close();    
            } catch (IOException e) {    
                e.printStackTrace();    
            }    
        }    
        try {  //關閉連線、釋放資源    
            closeableHttpClient.close();    
        } catch (IOException e) {    
            e.printStackTrace();    
        }      
        return response;    
    }    
      
    /**  
     * 傳送 http put 請求,引數以原生字串進行提交  
     * @param url  
     * @param encode  
     * @return  
     */    
    public static HttpResponse httpPutRaw(String url,String stringJson,Map<String,String> headers, String encode){    
        HttpResponse response = new HttpResponse();  
        if(encode == null){    
            encode = "utf-8";    
        }    
        //HttpClients.createDefault()等價於 HttpClientBuilder.create().build();     
        CloseableHttpClient closeableHttpClient = HttpClients.createDefault();     
        HttpPut httpput = new HttpPut(url);  
          
        //設定header  
        httpput.setHeader("Content-type", "application/json");      
        if (headers != null && headers.size() > 0) {  
            for (Map.Entry<String, String> entry : headers.entrySet()) {  
                httpput.setHeader(entry.getKey(),entry.getValue());  
            }  
        }  
        //組織請求引數    
        StringEntity stringEntity = new StringEntity(stringJson, encode);    
        httpput.setEntity(stringEntity);    
        String content = null;    
        CloseableHttpResponse  httpResponse = null;    
        try {    
            //響應資訊  
            httpResponse = closeableHttpClient.execute(httpput);    
            HttpEntity entity = httpResponse.getEntity();    
            content = EntityUtils.toString(entity, encode);    
            response.setBody(content);  
            response.setHeaders(httpResponse.getAllHeaders());  
            response.setReasonPhrase(httpResponse.getStatusLine().getReasonPhrase());  
            response.setStatusCode(httpResponse.getStatusLine().getStatusCode());  
        } catch (Exception e) {    
            e.printStackTrace();    
        }finally{    
            try {    
                httpResponse.close();    
            } catch (IOException e) {    
                e.printStackTrace();    
            }    
        }    
        try {    
            closeableHttpClient.close();  //關閉連線、釋放資源    
        } catch (IOException e) {    
            e.printStackTrace();    
        }      
        return response;    
    }    
    /**  
     * 傳送http delete請求  
     */    
    public static HttpResponse httpDelete(String url,Map<String,String> headers,String encode){    
        HttpResponse response = new HttpResponse();  
        if(encode == null){    
            encode = "utf-8";    
        }    
        String content = null;    
        //since 4.3 不再使用 DefaultHttpClient    
        CloseableHttpClient closeableHttpClient = HttpClientBuilder.create().build();     
        HttpDelete httpdelete = new HttpDelete(url);    
        //設定header  
        if (headers != null && headers.size() > 0) {  
            for (Map.Entry<String, String> entry : headers.entrySet()) {  
                httpdelete.setHeader(entry.getKey(),entry.getValue());  
            }  
        }  
        CloseableHttpResponse httpResponse = null;    
        try {    
            httpResponse = closeableHttpClient.execute(httpdelete);    
            HttpEntity entity = httpResponse.getEntity();    
            content = EntityUtils.toString(entity, encode);    
            response.setBody(content);  
            response.setHeaders(httpResponse.getAllHeaders());  
            response.setReasonPhrase(httpResponse.getStatusLine().getReasonPhrase());  
            response.setStatusCode(httpResponse.getStatusLine().getStatusCode());  
        } catch (Exception e) {    
            e.printStackTrace();    
        }finally{    
            try {    
                httpResponse.close();    
            } catch (IOException e) {    
                e.printStackTrace();    
            }    
        }    
        try {   //關閉連線、釋放資源    
            closeableHttpClient.close();    
        } catch (IOException e) {    
            e.printStackTrace();    
        }      
        return response;    
    }    
      
    /**  
     * 傳送 http post 請求,支援檔案上傳 
     */    
    public static HttpResponse httpPostFormMultipart(String url,Map<String,String> params, List<File> files,Map<String,String> headers,String encode){    
        HttpResponse response = new HttpResponse();  
        if(encode == null){    
            encode = "utf-8";    
        }    
        CloseableHttpClient closeableHttpClient = HttpClients.createDefault();     
        HttpPost httpost = new HttpPost(url);    
          
        //設定header  
        if (headers != null && headers.size() > 0) {  
            for (Map.Entry<String, String> entry : headers.entrySet()) {  
                httpost.setHeader(entry.getKey(),entry.getValue());  
            }  
        }  
        MultipartEntityBuilder mEntityBuilder = MultipartEntityBuilder.create();  
        mEntityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);  
        mEntityBuilder.setCharset(Charset.forName(encode));  
          
        // 普通引數  
        ContentType contentType = ContentType.create("text/plain",Charset.forName(encode));//解決中文亂碼  
        if (params != null && params.size() > 0) {  
            Set<String> keySet = params.keySet();  
            for (String key : keySet) {  
                mEntityBuilder.addTextBody(key, params.get(key),contentType);  
            }  
        }  
        //二進位制引數  
        if (files != null && files.size() > 0) {  
            for (File file : files) {  
                mEntityBuilder.addBinaryBody("file", file);  
            }  
        }  
        httpost.setEntity(mEntityBuilder.build());  
        String content = null;    
        CloseableHttpResponse  httpResponse = null;    
        try {    
            httpResponse = closeableHttpClient.execute(httpost);    
            HttpEntity entity = httpResponse.getEntity();    
            content = EntityUtils.toString(entity, encode);    
            response.setBody(content);  
            response.setHeaders(httpResponse.getAllHeaders());  
            response.setReasonPhrase(httpResponse.getStatusLine().getReasonPhrase());  
            response.setStatusCode(httpResponse.getStatusLine().getStatusCode());  
        } catch (Exception e) {    
            e.printStackTrace();    
        }finally{    
            try {    
                httpResponse.close();    
            } catch (IOException e) {    
                e.printStackTrace();    
            }    
        }    
        try {  //關閉連線、釋放資源    
            closeableHttpClient.close();    
        } catch (IOException e) {    
            e.printStackTrace();    
        }      
        return response;    
    }    
        
}

相關推薦

使用HttpClient 傳送 GETPOSTPUTDelete請求檔案

  import java.io.File;  import java.io.IOException;    import java.io.UnsupportedEncodingException;    import java.nio.charset.Charset;  i

SpringCloud 之 Fegin —— 傳送GETPOST請求以及檔案

                       深信自己通過學習理解寫出來的才是自己的 --

使用httpclient傳送getpost請求

原文地址 HttpClient 是 Apache Jakarta Common 下的子專案,可以用來提供高效的、最新的、功能豐富的支援 HTTP 協議的客戶端程式設計工具包,並且它支援 HTTP 協議最新的版本和建議。當前官網最新版介紹頁是:http://hc.apache.org/http

java HttpClient傳送getpost請求

    最近需要用到在A專案裡面發起請求去請求B專案的介面,所以用到了HttpClient,將工具類記錄下,可設定get、post方式,也可以設定session和cookie等header 一、工具類HttpClientUtil package Utils; imp

java apache commons HttpClient傳送getpost請求的學習整理

HttpClient 是我最近想研究的東西,以前想過的一些應用沒能有很好的實現,發現這個開源專案之後就有點眉目了,令人頭痛的cookie問題還是有辦法解決滴。在網上整理了一些東西,寫得很好,寄放在這裡。 HTTP 協議可能是現在 Internet 上使用得最多、最重要

httpClient傳送getpost引數形式總結

最近工作中接觸到httpClient類,於是簡單總結了下,發現形式並不複雜: 這裡對於get請求形式,比較簡單,只需要把引數加到地址上,一起執行即可 CloseableHttpAsyncClie

GETPOSTPUTDELETE的區別 和 用法

網關 到你 服務端 utf-8 option 數學 返回 由於 ces Http定義了與服務器交互的不同方法,最基本的方法有4種,分別是GET,POST,PUT,DELETE。URL全稱是資源描述符,我們可以這樣認為:一個URL地址,它用於描述一個網絡上的資源,而HTTP中

ASP.NET MVC 重點教程一週年版 第十一回 母版頁使用者自定義控制元件檔案

母版頁(Master) 1.母版頁是與Controller無關的,母版頁只是一個View檔案,而沒有任何Controller與之相對應。 2.其實在ASP.NET MVC中View的aspx與母版頁並不像WebForm中那樣緊密關聯。 例如我想更換一個aspx的母版頁,只要在Action中return

Java:使用HttpClient進行POSTGET請求以及檔案和下載

1.HttpClient2.本部落格簡單介紹一下POST和GET以及檔案下載的應用。程式碼如下:package net.mobctrl; import java.io.ByteArrayOutputStream; import java.io.File; import ja

GETPOSTPUTDELETE的區別

Http定義了與伺服器互動的不同方法,最基本的方法有4種,分別是GET,POST,PUT,DELETE。URL全稱是資源描述符,我們可以這樣認為:一個URL地址,它用於描述一個網路上的資源,而HTTP中的GET,POST,PUT,DELETE就對應著對這個資源的查,改,增

十三根據HDFS提供的API,實現檔案下載刪除重新命名移動

一、 根據HDFS提供的API,實現以下功能: 針對檔案: 上傳、下載、刪除、重新命名、移動 package HdfsApi; import java.io.File; import java.io.FileInputStream; import java.io.IOExc

Retrofit2快速入門使用檔案(單

前言 在開發專案中經常會遇到上傳頭像的問題,那我們如果使用Retrofit做網路請求時,如何進行使用,在文章的最後有最清晰的使用方法 Retrofit可以認為是Okhttp的 “升級版”,為什麼這麼說?那是因為其內部預設是基於OkHttp來進行

REST模式中HTTP請求方法(GETPOSTPUTDELETE

 一直在測試REST模式的WEB SERVICE介面,客戶端的HTTP的請求方式一般分為四種:GET、POST、PUT、DELETE,這四種請求方式有什麼不同呢。簡單的說,GET就是獲取資源,POST就是建立資源,PUT就是更新資源,DELETE就是刪除資源。具體來說:  

使用Socket 完成HTTP post方式的文字檔案 demo

   程式碼結構: Android端 Web端 最終結果    該demo具有很強的通用性,而且程式碼的複用性極高,基本上以後不需要再為檔案上傳花費太多時間,拿過去直接可以用。    剛開始從

關於Netty傳送http請求實現檔案

在傳送http請求的時候關鍵在於request的封裝 1、首先要先將上傳的檔案封裝到HttpPostRequestEncoder中 HttpRequest request1 = new DefaultFullHttpRequest( HttpVersion

基於OkHttp網路通訊工具類(傳送getpost請求檔案和下載)

一、為什麼要用OkHttp? okhttp是專注於提升網路連線效率的http客戶端。 優點: 1、它能實現同一ip和埠的請求重用一個socket,這種方式能大大降低網路連線的時間,和每次請求都建立socket,再斷開socket的方式相比,降低了伺服器伺服器的壓力。 2、okhttp 對

雜談——HTTP的兩種請求GETPOST的作用區別與本質

當面試的時候,考官問你:GET和POST的作用是什麼,它們又有什麼區別呢 這時候你該如何回答呢? 且讓我們來理一理思緒~ 開始入手web專案的夥伴們基本上都開始使用GET和POST請求了,那這兩種請求到底是什麼東西呢,它又有什麼作用? 今天我們來細細瞭解一下。GET和POST作

jsonp和GETPOST的跨域原理解析GETPOST的區別

同源策略: 同源策略是1995年 Netscape 公司引入瀏覽器的,目前瀏覽器都是實行這個策略, 同源策略是為了保證使用者資訊的安全,防止惡意的網站竊取資料的。 同源指的是三個

實現HTTP協議GetPost檔案功能——使用libcurl介面實現

        之前我們已經詳細介紹了WinHttp介面如何實現Http的相關功能。本文我將主要講解如何使用libcurl庫去實現相關功能。(轉載請指明出於breaksoftware的csdn部落格)         libcurl在http://curl.haxx.se/

實現HTTP協議GetPost檔案功能——使用WinHttp介面實現

        在《使用WinHttp介面實現HTTP協議Get、Post和檔案上傳功能》一文中,我已經比較詳細地講解了如何使用WinHttp介面實現各種協議。在最近的程式碼梳理中,我覺得Post和檔案上傳模組可以得到簡化,於是幾乎重寫了這兩個功能的程式碼。因為Get、Pos