使用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;    
    }    
        
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
HttpClient是一个用于发送HTTP请求的开源框架,可以通过它发送GET、POST、PUT、DELETE等各种类型的请求。 如果需要使用HttpClient发送HTTPS的POST请求,需要对HttpClient进行配置,以确保安全性。 首先,需要创建一个SSL连接,用于发送HTTPS请求。可以通过创建一个SSL连接工厂来实现,这个工厂会使用信任的CA证书来验证目标服务器的身份。 接下来,创建一个HttpClient实例,并设置SSL连接工厂。 然后,创建一个HttpPost对象,设置请求的URL和请求参数。 接着,设置请求头,包括标识请求类型为POST、设置Content-Type为application/x-www-form-urlencoded等。 最后,使用HttpClient的execute方法执行POST请求,并获取返回的响应。 下面是一个示例代码: ``` import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.ssl.SSLContextBuilder; import org.apache.http.ssl.TrustStrategy; import org.apache.http.util.EntityUtils; import javax.net.ssl.SSLContext; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; public class HttpsPostExample { public static void main(String[] args) throws Exception { // 创建SSL连接工厂 SSLContext sslContext = SSLContextBuilder.create() .loadTrustMaterial(new TrustStrategy() { public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { return true; // 所有证书都被信任 } }) .build(); // 创建HttpClient实例,并设置SSL连接工厂 CloseableHttpClient httpClient = HttpClients.custom() .setSSLContext(sslContext) .build(); // 创建HttpPost对象,并设置URL和请求参数 HttpPost httpPost = new HttpPost("https://example.com"); String requestBody = "param1=value1&param2=value2"; httpPost.setEntity(new StringEntity(requestBody)); // 设置请求头 httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded"); // 发送POST请求,并获取响应 CloseableHttpResponse response = httpClient.execute(httpPost); String responseBody = EntityUtils.toString(response.getEntity()); // 输出响应结果 System.out.println(responseBody); // 关闭连接 response.close(); httpClient.close(); } } ``` 以上就是使用HttpClient发送HTTPS的POST请求的方法。通过SSL连接工厂的设置,可以确保请求的安全性。在实际使用中,可以根据需要设置请求参数、请求头等。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值