<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.3</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.3</version>
</dependency>
public static void main(String[] args) throws Exception {
byte[] b = getImage("14598222157082.png")
HttpClient httpClient = HttpClients.createDefault()
HttpPost httppost = new HttpPost("http://localhost/test")
MultipartEntityBuilder mEntityBuilder = MultipartEntityBuilder.create()
mEntityBuilder.addBinaryBody("file",b,ContentType.MULTIPART_FORM_DATA,"14598222157082.png")
httppost.setEntity(mEntityBuilder.build())
HttpResponse response = httpClient.execute(httppost)
Header[] hs= response.getAllHeaders()
for(Header h:hs)System.out.println(h.getName()+":"+h.getValue())
InputStream in=response.getEntity().getContent()
save(in, "result.png")
}
public static void save(InputStream in,String path) throws IOException{
OutputStream out =new FileOutputStream(path)
int l
int n=0
//不要使用in.available() 容易丢失数据
while ((l = in.read()) != -1) {
n++
out.write(l)
}
out.flush()
out.close()
}