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
| package com.yzw.http; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.mime.HttpMultipartMode; import org.apache.http.entity.mime.MultipartEntityBuilder; import org.apache.http.entity.mime.content.FileBody; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import java.io.File; import java.io.IOException; import java.nio.charset.Charset; import java.util.HashMap; import java.util.Map;
public class Test { public static String httpClientUploadFile(String url, File file, Map<String,String> params) { CloseableHttpClient httpClient = HttpClients.createDefault(); String result = ""; String boundary ="--------------20200103121104567"; try { HttpPost httpPost = new HttpPost(url); httpPost.setHeader("Content-Type","multipart/form-data; boundary="+boundary);
MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setCharset(Charset.forName("UTF-8")); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); builder.setBoundary(boundary); builder.addPart("uploadimg",new FileBody(file));
for (Map.Entry<String, String> entry : params.entrySet()) { builder.addTextBody(entry.getKey(), entry.getValue() ); } HttpEntity entity = builder.build(); httpPost.setEntity(entity); HttpResponse response = httpClient.execute(httpPost); HttpEntity responseEntity = response.getEntity(); if (responseEntity != null) { result = EntityUtils.toString(responseEntity, Charset.forName("UTF-8")); } } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } finally { try { httpClient.close(); } catch (IOException e) { e.printStackTrace(); } } System.err.println("result"+result); return result; }
public static void main(String[] args) { Map<String,String> params = new HashMap<>();
String filePath = new String("C:\\Users\\27184\\Desktop\\项目\\新建文件夹\\的文案.png"); String httpPost = "http://1.w2wz.com/upload.php"; httpClientUploadFile(httpPost,new File(filePath),params); } }
|