`
虎嗅蔷薇
  • 浏览: 7474 次
社区版块
存档分类
最新评论

HttpClient发送GET POST DELETE PUT操作

 
阅读更多
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; 
    } 
     
分享到:
评论

相关推荐

    http接口通用调试工具,支持get、post、put、patch、delete方法

    本文将深入探讨一个通用的HTTP接口调试工具,该工具支持GET、POST、PUT、PATCH和DELETE等常见HTTP请求方法,并且专注于处理JSON格式的数据。这将帮助开发者在开发和测试过程中更加高效地进行接口调用与验证。 首先...

    Android-HttpClient工具类简单轻松的实现getpostput和delete请求

    在Android开发过程中,网络请求是不可或缺的一部分,而`HttpClient`是一个强大的HTTP客户端库,它允许开发者执行各种HTTP操作,如GET、POST、PUT和DELETE。本篇文章将详细讲解如何使用`HttpClient`工具类来简化这些...

    java http 发送 put delete post get请求

    本篇将详细解释如何使用Java发送PUT、DELETE、POST和GET这四种主要的HTTP请求。 PUT请求常用于更新已有资源,它的特点是替换目标URL指定的整个资源。在Java中,可以使用HttpURLConnection或Apache HttpClient库来...

    HttpClient发送http请求(post和get)需要的jar包+内符java代码案例+注解详解

    通过HttpClient,开发者可以方便地创建HTTP客户端,执行各种HTTP请求,包括GET、POST、PUT、DELETE等,并接收响应。在Java项目中,如果需要与Web服务交互,HttpClient是一个常见的选择。 1. **HTTP请求**:HTTP(超...

    HttpClient工具类

    http工具类,基于java,封装HttpClient的四种提交方式:post,get,delete,put

    httpclient

    1. **多种HTTP方法支持**:HttpClient支持GET、POST、PUT、DELETE等多种HTTP方法,满足不同类型的HTTP操作需求。 2. **连接管理**:HttpClient可以自动管理HTTP连接,如复用连接、控制连接池大小,从而提高效率并...

    android httpclient demo

    本文将深入探讨如何使用`Android HttpClient`进行HTTP请求,包括GET、POST、PUT和DELETE等常见操作,并基于提供的"android httpclient demo"项目,解释其结构和运行流程。 首先,`Android HttpClient`是Apache ...

    浏览器发送模拟httpclient软件

    1. **请求构造**:用户可以输入URL、选择HTTP方法(GET、POST、PUT、DELETE等),并添加请求头和查询参数。 2. **数据提交**:对于POST请求,用户可以提供请求体,比如JSON、XML或者表单数据。 3. **响应查看**:...

    httpclient.jar包下载.zip

    除了基本的GET和POST,HttpClient还支持PUT、DELETE等其他HTTP方法,以及更复杂的特性,如HTTP连接管理、重试策略、身份验证、Cookie处理等。 网络协议方面,HttpClient遵循HTTP/1.1标准,并且可以与HTTPS(即安全...

    httpclientutil

    5. **HTTP 方法**:HttpClient 支持 GET、POST、PUT、DELETE 等HTTP方法,每种方法对应不同的资源操作。在这个例子中,很可能是使用 POST 方法发送 JSON 数据。 6. **设置请求头**:在发送请求时,我们可能需要设置...

    Http(get)请求数据Android Studio使用HttpClient

    虽然本教程只涉及GET请求,`HttpClient`也支持其他HTTP方法,如POST、PUT、DELETE等。使用`HttpPost`、`HttpPut`、`HttpDelete`分别代表这些方法,设置请求参数的方式会有所不同,比如POST请求需要使用`...

    javaTest_getpost

    本文将深入探讨这两种...这个"javaTest_getpost"项目提供了一个很好的实践示例,有助于加深对这些概念的理解。在实际项目中,可以根据需要调整参数、处理不同类型的响应,甚至实现更复杂的HTTP操作,如PUT、DELETE等。

    php中http请求封装HttpClient精华中的经典代码

    2. **HTTP方法支持**:包括GET、POST、PUT、DELETE等多种HTTP请求方法。 3. **请求参数处理**:对于POST请求,需要处理表单数据、JSON数据或文件上传;对于GET请求,可能需要添加查询参数。 4. **请求头管理**:设置...

    HttpClient4.3需要的jar

    它支持各种HTTP方法,如GET、POST、PUT、DELETE等,以及HTTP/1.1协议的完整特性。 2. **GET与POST请求**: - **GET**:GET是HTTP中最常见的请求方法,用于获取资源。HttpClient通过`HttpGet`类来创建并发送GET请求...

    commons-httpclient-2.0

    3. **HttpMethod**:表示HTTP请求的抽象类,包括GET、POST、PUT、DELETE等具体方法。每个HttpMethod实例代表一次HTTP请求。 4. **RequestEntity**和**ResponseEntity**:分别用于封装HTTP请求和响应的实体内容,支持...

    httpClienthttpClient

    HttpClient支持各种HTTP方法(如GET、POST、PUT、DELETE等),同时也支持连接管理、重试策略、缓存控制等功能。 在HttpClient中,主要的概念有以下几个: 1. **HttpClient实例**:HttpClient对象是执行HTTP请求的...

    httpclient jar包

    - 它支持多种HTTP方法,如GET、POST、PUT、DELETE等,同时支持HTTP连接管理、重定向处理、身份验证、cookies管理等功能。 2. **POST提交**: - POST方法常用于向服务器发送数据,比如提交表单或上传文件。...

    httpclient Demo

    除了基本的GET和POST,HttpClient还支持PUT、DELETE等HTTP方法,以及自定义请求头和HTTP实体。 在处理HTTP请求时,可能需要处理身份验证、Cookie管理、连接池和重定向。HttpClient提供了`CredentialsProvider`用于...

Global site tag (gtag.js) - Google Analytics