Httpclient-(get、post(application/json)、post(application/form-data)、download、upload)
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 package com.sskd.drm.utils; 2 3 import java.util.*; 4 5 import com.alibaba.fastjson.JSON; 6 import org.apache.http.*; 7 import org.apache.http.client.entity.UrlEncodedFormEntity; 8 import org.apache.http.client.methods.*; 9 import org.apache.http.entity.ContentType; 10 import org.apache.http.entity.StringEntity; 11 import org.apache.http.entity.mime.MultipartEntityBuilder; 12 import org.apache.http.entity.mime.content.FileBody; 13 import org.apache.http.message.BasicNameValuePair; 14 import org.apache.http.util.EntityUtils; 15 import java.io.IOException; 16 17 import org.apache.http.impl.client.HttpClients; 18 import org.apache.http.impl.client.CloseableHttpClient; 19 import org.apache.http.ssl.SSLContexts; 20 import javax.net.ssl.SSLContext; 21 import org.apache.http.conn.ssl.NoopHostnameVerifier; 22 import java.io.*; 23 import java.io.File; 24 25 /** 26 * @name HttpClientUtils 27 * @Description Httpclient工具类 28 * @author Mr.bai 29 * @time 2020/5/15 13:06 30 * @version 1.0 31 */ 32 public class HttpClientUtils { 33 34 /** 35 * get请求 36 * @param url url地址 37 * @param parameters 参数map集 38 * @param headers 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(new BasicNameValuePair(k, v)); 54 } 55 } 56 String urlencoded =EntityUtils.toString(new UrlEncodedFormEntity(formData, Consts.UTF_8)); 57 if(basicUrl.contains("?")) { 58 basicUrl += urlencoded; 59 }else { 60 basicUrl+= "?"+urlencoded; 61 } 62 } 63 //纯url 64 HttpGet get=new HttpGet(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 return getResult(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 return result; 86 } 87 88 /** 89 * post(application/form-data)请求 90 * @param url url地址 91 * @param body 参数集 如果参数内需要传输文件,传File 92 * @param headers 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 =new HttpPost(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) instanceof File){ 104 File file = (File) body.get(key); 105 FileBody fileBody = new FileBody(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 return getResult(response); 124 }catch(Exception e ) { 125 System.err.println("请求出错\n错误信息:" +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 * @param url url地址 141 * @param body 参数集 142 * @param headers header配置 143 * @return 144 */ 145 public static String postJsonrequest(String url , Map<Object, Object> body , Map<Object, Object> headers){ 146 HttpPost post =new HttpPost(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 return getResult(response); 162 }catch (Exception e) { 163 System.err.println("请求出错\n错误信息:" +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 * @param url 下载文件地址 180 * @param localfileName 本地储存路径, 181 * @param remotefileName 服务器资源路径 182 */ 183 public static void downloadfile(String url,String localfileName,String remotefileName) { 184 FileOutputStream output = null; 185 InputStream in = null; 186 CloseableHttpClient httpclient=getignoreSSLClient(); 187 try { 188 HttpGet get=new HttpGet(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 = new File(localfileName); 198 199 if(! localfile.exists()) { 200 localfile.createNewFile(); 201 } 202 output=new FileOutputStream(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 * @param localfilepath 文件路径 230 * @param url 上传文件的url 231 */ 232 public static String uploadfile(String localfilepath,String url) { 233 CloseableHttpClient httpclient=getignoreSSLClient(); 234 try { 235 HttpPost post = new HttpPost(url); 236 FileBody bin=new FileBody(new File(localfilepath)); 237 HttpEntity entity = MultipartEntityBuilder.create().addPart("audioData",bin).build(); 238 post.setEntity(entity); 239 HttpResponse response=httpclient.execute(post); 240 return getResult(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 static CloseableHttpClient 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(new NoopHostnameVerifier()).build(); 264 }catch(Exception e) { 265 System.err.println("配置跳过ssl证书出错:" + e.getMessage()); 266 } 267 return client; 268 } 269 270 private static String getResult(HttpResponse response) throws IOException { 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 return result; 279 } 280 } 281 System.err.println("请求出错\n状态码:"+errorCode+"\n错误信息"+EntityUtils.toString(entity,"utf-8")); 282 return null; 283 } 284 }