上传文件到指定URL(put方式,其他类似)

public void uploadFile(String url,String fileName) throws Exception{
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {
        HttpPut httpput = new HttpPut(url);

        FileBody bin = new FileBody(new File(fileName));
        StringBody comment = new StringBody("A binary file of some kind", ContentType.TEXT_PLAIN);

        HttpEntity reqEntity = MultipartEntityBuilder.create()
                .addPart("bin", bin)
                .addPart("comment", comment)
                .build();


        httpput.setEntity(reqEntity);

        System.out.println("executing request " + httpput.getRequestLine());
        CloseableHttpResponse response = httpclient.execute(httpput);
        try {
            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            HttpEntity resEntity = response.getEntity();
            if (resEntity != null) {
                System.out.println("Response content length: " +    resEntity.getContentLength());
            }
            EntityUtils.consume(resEntity);
        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }

}

一下是pom中需要用到的依赖
 -->

    Id>org.apache.httpcomponentnents
    httpclient
    4.5.6

 -->

    Id>org.apache.httpcomponentnents
    httpmime
    4.5.6

你可能感兴趣的:(新知识的学习)