摘要:url.contains("=")){49if(parameters!=null&¶meters.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 }