Httpclient-(get、post(application/json)、post(application/form-data)、download、upload)

摘要:
url.contains("=")){49if(parameters!=null&&parameters.size()˃0){50for(Map.Entryentry:parameters.entrySet()){51Stringk=entry.getKey();52Stringv=entry.getValue();53formData.add(newBasicNameValuePair(k,v));54}55}56Stringurlencoded=EntityUtils.toString(newUrlEncodedFormEntity(formData,Consts.UTF_8));57if(basicUrl.contains("?")){58basicUrl+=urlencoded;59}else{60basicUrl+="?"+urlencoded;61}62}63//纯url64HttpGetget=newHttpGet(basicUrl);65if(headers!

pom文件引入包:

     <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpmime</artifactId>
        </dependency>
<dependency>
<groupId>com.alibaba</groupId>
       <artifactId>fastjson</artifactId>
       <version>1.2.62</version>
     </dependency>

HttpClientUtils参考:

1 packagecom.sskd.drm.utils;
2 
3 import java.util.*;
4 
5 importcom.alibaba.fastjson.JSON;
6 import org.apache.http.*;
7 importorg.apache.http.client.entity.UrlEncodedFormEntity;
8 import org.apache.http.client.methods.*;
9 importorg.apache.http.entity.ContentType;
10 importorg.apache.http.entity.StringEntity;
11 importorg.apache.http.entity.mime.MultipartEntityBuilder;
12 importorg.apache.http.entity.mime.content.FileBody;
13 importorg.apache.http.message.BasicNameValuePair;
14 importorg.apache.http.util.EntityUtils;
15 importjava.io.IOException;
16 
17 importorg.apache.http.impl.client.HttpClients;
18 importorg.apache.http.impl.client.CloseableHttpClient;
19 importorg.apache.http.ssl.SSLContexts;
20 importjavax.net.ssl.SSLContext;
21 importorg.apache.http.conn.ssl.NoopHostnameVerifier;
22 import java.io.*;
23 importjava.io.File;
24 
25 /**
26 * @name HttpClientUtils
27 * @Description Httpclient工具类
28 * @authorMr.bai
29 * @time  2020/5/15 13:06
30 * @version1.0
31  */
32 public classHttpClientUtils {
33 
34     /**
35 * get请求
36 * @paramurl url地址
37 * @paramparameters 参数map集
38 * @paramheaders header集
39 * @return
40      */
41     public static String getrequest(String url,Map<String, String> parameters,Map<String,String>headers){
42         String basicUrl=url;
43         String result=null;
44         CloseableHttpClient httpclient=getignoreSSLClient();
45         List<NameValuePair> formData=new ArrayList<>();
46         try{
47             //参数分离
48             if(!url.contains("=")) {
49                 if(parameters !=null && parameters.size()>0) {
50                     for(Map.Entry<String,String>entry:parameters.entrySet()) {
51                         String k =entry.getKey();
52                         String v=entry.getValue();
53                         formData.add(newBasicNameValuePair(k, v));
54 }
55 }
56                 String urlencoded =EntityUtils.toString(newUrlEncodedFormEntity(formData, Consts.UTF_8));
57                 if(basicUrl.contains("?")) {
58                     basicUrl +=urlencoded;
59                 }else{
60                     basicUrl+= "?"+urlencoded;
61 }
62 }
63             //纯url
64             HttpGet get=newHttpGet(basicUrl);
65             if(headers !=null && headers.size()>0) {
66                 for(Map.Entry<String, String>entry:headers.entrySet()) {
67 get.setHeader(entry.getKey(),entry.getValue());
68 }
69             }else{
70                 get.setHeader(null);
71 }
72             HttpResponse response=httpclient.execute(get);
73             returngetResult(response);
74         }catch(IOException e) {
75 e.printStackTrace();
76         }finally{
77             try{
78                 if(httpclient!=null) {
79 httpclient.close();
80 }
81             }catch(IOException e) {
82 e.printStackTrace();
83 }
84 }
85         returnresult;
86 }
87 
88     /**
89 * post(application/form-data)请求
90 * @paramurl url地址
91 * @parambody 参数集 如果参数内需要传输文件,传File
92 * @paramheaders header配置
93 * @return
94      */
95     public static String postformData(String url,Map<String, Object> body,Map<String, String>headers){
96         CloseableHttpClient httpclient =getignoreSSLClient();
97         try{
98             HttpPost post =newHttpPost(url);
99             //请求表单参数
100             MultipartEntityBuilder reqEntity =MultipartEntityBuilder.create();
101             if (body != null && body.size() > 0){
102                 for(String key : body.keySet()) {
103                     if (body.get(key) instanceofFile){
104                         File file =(File) body.get(key);
105                         FileBody fileBody = newFileBody(file);
106 reqEntity.addPart(key, fileBody);
107                     }else{
108 reqEntity.addTextBody(key, body.get(key).toString(),ContentType.TEXT_PLAIN);
109 }
110 }
111                 System.out.println("post(application/form-data)请求,构造参数完毕!");
112 }
113 post.setEntity(reqEntity.build());
114             //设置header
115             if(headers !=null && headers.size()>0) {
116                 for(String key : headers.keySet()) {
117 post.setHeader(key,headers.get(key));
118 }
119             }else{
120                 post.setHeader(null);
121 }
122             HttpResponse response =httpclient.execute(post);
123             returngetResult(response);
124         }catch(Exception e ) {
125             System.err.println("请求出错
错误信息:" +e.getMessage());
126         }finally{
127             try{
128                 if(httpclient!=null) {
129 httpclient.close();
130 }
131             }catch(Exception e) {
132 e.printStackTrace();
133 }
134 }
135         return null;
136 }
137 
138     /**
139 * post(application/json)
140 * @paramurl url地址
141 * @parambody 参数集
142 * @paramheaders header配置
143 * @return
144      */
145     public static String postJsonrequest(String url , Map<Object, Object> body , Map<Object, Object>headers){
146         HttpPost post =newHttpPost(url);
147         CloseableHttpClient httpclient=getignoreSSLClient();
148         try{
149             if(headers !=null && headers.size()>0) {
150                 for(Map.Entry<Object, Object>entry:headers.entrySet()) {
151 post.setHeader(entry.getKey().toString(),entry.getValue().toString());
152 }
153             }else{
154                 post.setHeader("Content-Type","application/json;charset=UTF-8");
155                 //header设置完毕
156 }
157             //body转string,处理entity传入httpEntity
158             StringEntity newEntity=new StringEntity(JSON.toJSONString(body),"utf-8");
159 post.setEntity(newEntity);;
160             HttpResponse response=httpclient.execute(post);
161             returngetResult(response);
162         }catch(Exception e) {
163             System.err.println("请求出错
错误信息:" +e.getMessage());
164         }finally{
165             try{
166                 if(httpclient!=null) {
167 httpclient.close();
168 }
169 
170             }catch(Exception e) {
171 e.printStackTrace();
172 }
173 }
174         return null;
175 }
176 
177     /**
178 * 下载文件
179 * @paramurl 下载文件地址
180 * @paramlocalfileName 本地储存路径,
181 * @paramremotefileName 服务器资源路径
182      */
183     public static voiddownloadfile(String url,String localfileName,String remotefileName) {
184         FileOutputStream output = null;
185         InputStream in = null;
186         CloseableHttpClient httpclient=getignoreSSLClient();
187         try{
188             HttpGet get=newHttpGet(url);
189             get.addHeader("fileName",remotefileName );
190             HttpResponse response=httpclient.execute(get);
191             HttpEntity entity =response.getEntity();
192             in =entity.getContent();
193             long length =entity.getContentLength();
194             if (length <= 0) {
195                 return;
196 }
197             File localfile = newFile(localfileName);
198 
199             if(!localfile.exists()) {
200 localfile.createNewFile();
201 }
202             output=newFileOutputStream(localfile);
203             byte[] buffer = new byte[4096];
204             int readLength = 0;
205             while ((readLength=in.read(buffer)) > 0) {
206                 byte[] bytes = new byte[readLength];
207                 System.arraycopy(buffer, 0, bytes, 0, readLength);
208 output.write(bytes);
209 }
210 output.flush();
211         }catch(Exception e) {
212 e.printStackTrace();
213         }finally{
214             try{
215                 if(in !=null) {
216 in.close();
217 }
218                 if(output !=null) {
219 output.close();
220 }
221             }catch(IOException e) {
222 e.printStackTrace();
223 }
224 }
225 }
226 
227     /**
228 * 上传文件
229 * @paramlocalfilepath 文件路径
230 * @paramurl 上传文件的url
231      */
232     public staticString uploadfile(String localfilepath,String url) {
233         CloseableHttpClient httpclient=getignoreSSLClient();
234         try{
235             HttpPost post = newHttpPost(url);
236             FileBody bin=new FileBody(newFile(localfilepath));
237             HttpEntity entity = MultipartEntityBuilder.create().addPart("audioData",bin).build();
238 post.setEntity(entity);
239             HttpResponse response=httpclient.execute(post);
240             returngetResult(response);
241         }catch(Exception e) {
242 e.printStackTrace();
243         }finally{
244             try{
245                 if(httpclient!=null) {
246 httpclient.close();
247 }
248             }catch(Exception e) {
249 e.printStackTrace();
250 }
251 }
252         return null;
253 }
254 
255     /**
256 * ssl安全跳过
257 * @return
258      */
259     private staticCloseableHttpClient getignoreSSLClient() {
260         CloseableHttpClient client =null;
261         try{
262             SSLContext sslContext=SSLContexts.custom().loadTrustMaterial(null, (x509Certificates, s) -> true).build();
263             client=HttpClients.custom().setSSLContext(sslContext).setSSLHostnameVerifier(newNoopHostnameVerifier()).build();
264         }catch(Exception e) {
265             System.err.println("配置跳过ssl证书出错:" +e.getMessage());
266 }
267         returnclient;
268 }
269 
270     private static String getResult(HttpResponse response) throwsIOException {
271         HttpEntity entity=response.getEntity();
272         int errorCode=response.getStatusLine().getStatusCode();
273         if (HttpStatus.SC_OK==errorCode){
274             if (entity != null){
275                 String result =EntityUtils.toString(entity,"utf-8");
276                 //关闭entity
277 EntityUtils.consume(entity);
278                 returnresult;
279 }
280 }
281         System.err.println("请求出错
状态码:"+errorCode+"
错误信息"+EntityUtils.toString(entity,"utf-8"));
282         return null;
283 }
284 }

免责声明:文章转载自《Httpclient-(get、post(application/json)、post(application/form-data)、download、upload)》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇ansible-乱tp5笔记(一)下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

python基础练习题(题目 递归输出)

day19 --------------------------------------------------------------- 实例027:递归输出 题目 利用递归函数调用方式,将所输入的5个字符,以相反顺序打印出来。 分析:相反顺序可以用列表来,直接pop方法。 1 def reverseprint(a): 2 lit = list(...

GET和POST请求区别

关于http协议GET和POST方法的区别我们可以从各处得到比较一致的答案,今天我们来填一个面试中可能碰到的一个坑。 当面试官问你“你觉得GET和POST有什么区别"时,我们可能会想到以下几点(来源于网络): GET在浏览器回退时是无害的,而POST会再次提交请求。 GET产生的URL地址可以被Bookmark,而POST不可以。 GET请求会被浏览器主...

delphi 对应 c# 的一些函数及类型的转换方法【原】

例一 实现目的:将字符串中每一个字符转成二进制(比如 'Data' 中的 D 转成 00100010 ,整个就是 00100010100001100010111010000110) 处理逻辑:string result = StrToByte("Data"); result结果是00100010100001100010111010000110   1、实际...

ASP.NET中Get和Post的用法 Request.QueryString,Request.Form,Request.Params的区别

表单form的提交有两种方式,一种是get的方法,一种是post 的方法.看下面代码,理解ASP.NET Get和Post两种提交的区别:   代码 view plaincopy to clipboardprint?< form id="form1" method="get" runat="server"> < div>...

ASP.Net Core 中使用Zookeeper搭建分布式环境中的配置中心系列一:使用Zookeeper.Net组件演示基本的操作

前言:马上要过年了,祝大家新年快乐!在过年回家前分享一篇关于Zookeeper的文章,我们都知道现在微服务盛行,大数据、分布式系统中经常会使用到Zookeeper,它是微服务、分布式系统中必不可少的分布式协调框架。它的作用体现在分布式系统中解决了配置中心的问题,以及解决了在分布式环境中不同进程之间争夺资源的问题,也就是分布式锁的功能以及分布式消息队列功能等...

Flutter实战视频-移动电商-43.详细页_补充首页跳转到详细页

43.详细页_补充首页跳转到详细页 首页轮播点击到详细页 修改我们轮播这里的代码:SwiperDiy这个类这里的代码 returnInkWell( onTap: (){ Application.router.navigateTo(context, '/detail?id=${swiperDat...