Httpclient工具类
1 | 一、引入依赖包 |
1 2 3 4 5 6 7 8 9 10 11 12 13 | <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> |
二、工具类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 | package com.sskd.drm.utils; import java.util.*; import com.alibaba.fastjson.JSON; import org.apache.http.*; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.*; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; import org.apache.http.entity.mime.MultipartEntityBuilder; import org.apache.http.entity.mime.content.FileBody; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import java.io.IOException; import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.ssl.SSLContexts; import javax.net.ssl.SSLContext; import org.apache.http.conn.ssl.NoopHostnameVerifier; import java.io.*; import java.io.File; /** * @name HttpClientUtils * @Description Httpclient工具类 * @author Mr.bai * @time 2020/5/15 13:06 * @version 1.0 */ public class HttpClientUtils { /** * get请求 * @param url url地址 * @param parameters 参数map集 * @param headers header集 * @return */ public static String getrequest(String url,Map<String, String> parameters,Map<String,String> headers){ String basicUrl=url; String result= null ; CloseableHttpClient httpclient=getignoreSSLClient(); List<NameValuePair> formData= new ArrayList<>(); try { //参数分离 if (!url.contains( "=" )) { if (parameters != null && parameters.size()> 0 ) { for (Map.Entry<String,String> entry:parameters.entrySet()) { String k =entry.getKey(); String v=entry.getValue(); formData.add( new BasicNameValuePair(k, v)); } } String urlencoded =EntityUtils.toString( new UrlEncodedFormEntity(formData, Consts.UTF_8)); if (basicUrl.contains( "?" )) { basicUrl += urlencoded; } else { basicUrl+= "?" +urlencoded; } } //纯url HttpGet get= new HttpGet(basicUrl); if (headers != null && headers.size()> 0 ) { for (Map.Entry<String, String> entry:headers.entrySet()) { get.setHeader(entry.getKey(),entry.getValue()); } } else { get.setHeader( null ); } HttpResponse response=httpclient.execute(get); return getResult(response); } catch (IOException e) { e.printStackTrace(); } finally { try { if (httpclient!= null ) { httpclient.close(); } } catch (IOException e) { e.printStackTrace(); } } return result; } /** * post(application/form-data)请求 * @param url url地址 * @param body 参数集 如果参数内需要传输文件,传File * @param headers header配置 * @return */ public static String postformData(String url,Map<String, Object> body,Map<String, String> headers){ CloseableHttpClient httpclient = getignoreSSLClient(); try { HttpPost post = new HttpPost(url); //请求表单参数 MultipartEntityBuilder reqEntity = MultipartEntityBuilder.create(); if (body != null && body.size() > 0 ){ for (String key : body.keySet()) { if (body.get(key) instanceof File){ File file = (File) body.get(key); FileBody fileBody = new FileBody(file); reqEntity.addPart(key, fileBody); } else { reqEntity.addTextBody(key, body.get(key).toString(),ContentType.TEXT_PLAIN); } } System.out.println( "post(application/form-data)请求,构造参数完毕!" ); } post.setEntity(reqEntity.build()); //设置header if (headers != null && headers.size()> 0 ) { for (String key : headers.keySet()) { post.setHeader(key,headers.get(key)); } } else { post.setHeader( null ); } HttpResponse response = httpclient.execute(post); return getResult(response); } catch (Exception e ) { System.err.println( "请求出错\n错误信息:" +e.getMessage()); } finally { try { if (httpclient!= null ) { httpclient.close(); } } catch (Exception e) { e.printStackTrace(); } } return null ; } /** * post(application/json) * @param url url地址 * @param body 参数集 * @param headers header配置 * @return */ public static String postJsonrequest(String url , Map<Object, Object> body , Map<Object, Object> headers){ HttpPost post = new HttpPost(url); CloseableHttpClient httpclient=getignoreSSLClient(); try { if (headers != null && headers.size()> 0 ) { for (Map.Entry<Object, Object> entry:headers.entrySet()) { post.setHeader(entry.getKey().toString(),entry.getValue().toString()); } } else { post.setHeader( "Content-Type" , "application/json;charset=UTF-8" ); //header设置完毕 } //body转string,处理entity传入httpEntity StringEntity newEntity= new StringEntity(JSON.toJSONString(body), "utf-8" ); post.setEntity(newEntity);; HttpResponse response=httpclient.execute(post); return getResult(response); } catch (Exception e) { System.err.println( "请求出错\n错误信息:" +e.getMessage()); } finally { try { if (httpclient!= null ) { httpclient.close(); } } catch (Exception e) { e.printStackTrace(); } } return null ; } /** * 下载文件 * @param url 下载文件地址 * @param localfileName 本地储存路径, * @param remotefileName 服务器资源路径 */ public static void downloadfile(String url,String localfileName,String remotefileName) { FileOutputStream output = null ; InputStream in = null ; CloseableHttpClient httpclient=getignoreSSLClient(); try { HttpGet get= new HttpGet(url); get.addHeader( "fileName" ,remotefileName ); HttpResponse response=httpclient.execute(get); HttpEntity entity =response.getEntity(); in = entity.getContent(); long length = entity.getContentLength(); if (length <= 0 ) { return ; } File localfile = new File(localfileName); if (! localfile.exists()) { localfile.createNewFile(); } output= new FileOutputStream(localfile); byte [] buffer = new byte [ 4096 ]; int readLength = 0 ; while ((readLength=in.read(buffer)) > 0 ) { byte [] bytes = new byte [readLength]; System.arraycopy(buffer, 0 , bytes, 0 , readLength); output.write(bytes); } output.flush(); } catch (Exception e) { e.printStackTrace(); } finally { try { if (in != null ) { in.close(); } if (output != null ) { output.close(); } } catch (IOException e) { e.printStackTrace(); } } } /** * 上传文件 * @param localfilepath 文件路径 * @param url 上传文件的url */ public static String uploadfile(String localfilepath,String url) { CloseableHttpClient httpclient=getignoreSSLClient(); try { HttpPost post = new HttpPost(url); FileBody bin= new FileBody( new File(localfilepath)); HttpEntity entity = MultipartEntityBuilder.create().addPart( "audioData" ,bin).build(); post.setEntity(entity); HttpResponse response=httpclient.execute(post); return getResult(response); } catch (Exception e) { e.printStackTrace(); } finally { try { if (httpclient!= null ) { httpclient.close(); } } catch (Exception e) { e.printStackTrace(); } } return null ; } /** * ssl安全跳过 * @return */ private static CloseableHttpClient getignoreSSLClient() { CloseableHttpClient client = null ; try { SSLContext sslContext=SSLContexts.custom().loadTrustMaterial( null , (x509Certificates, s) -> true ).build(); client=HttpClients.custom().setSSLContext(sslContext).setSSLHostnameVerifier( new NoopHostnameVerifier()).build(); } catch (Exception e) { System.err.println( "配置跳过ssl证书出错:" + e.getMessage()); } return client; } private static String getResult(HttpResponse response) throws IOException { HttpEntity entity=response.getEntity(); int errorCode= response.getStatusLine().getStatusCode(); if (HttpStatus.SC_OK==errorCode){ if (entity != null ){ String result =EntityUtils.toString(entity, "utf-8" ); //关闭entity EntityUtils.consume(entity); return result; } } System.err.println( "请求出错\n状态码:" +errorCode+ "\n错误信息" +EntityUtils.toString(entity, "utf-8" )); return null ; } } |
分类:
JAVA
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
2021-03-11 Java线程封闭—ThreadLocal