使用HttpClient 發送 GET、POST、PUT、Delete請求及文件上傳


package org.caeit.cloud.dev.util;  
  
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;    
    }    
        
}    

發送Get請求:

HttpResponse httpGet(String url,Map<String,String> headers,String encode)

發送Post請求,同表單Post提交

HttpResponse httpPostForm(String url,Map<String,String> params, Map<String,String> headers,String encode)

發送Post Raw請求

HttpResponse httpPostRaw(String url,String stringJson,Map<String,String> headers, String encode)

發送Put Raw請求

HttpResponse httpPutRaw(String url,String stringJson,Map<String,String> headers, String encode)

發送Delete請求

HttpResponse httpDelete(String url,Map<String,String> headers,String encode)

 

 

說明:

1、since 4.3 不再使用 DefaultHttpClient

2、UrlEncodedFormEntity 與 StringEntity 區別

2.1、UrlEncodedFormEntity()的形式比較單一,只能是普通的鍵值對,局限性相對較大。

2.2、而StringEntity()的形式比較自由,只要是字符串放進去,不論格式都可以。

3、以raw方式發送請求時,需指定 Content type:httpost.setHeader("Content-type", "application/json");  否則默認使用 Content type 'text/plain;charset=UTF-8'

 

注:http://huangqiqing123.iteye.com/blog/2344680


免責聲明!

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



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