使用httpclient上传文件

public static String UploadFileByHttpClient(String url,Map<String,Object> params,String fileName) {
        String result = "";
        CloseableHttpClient httpClient = createSSLClientDefault();;
        CloseableHttpResponse  response = null;
        InputStream content = null;
        BufferedReader in = null;
        try {
            HttpPost httpPost = new HttpPost(url);
            //HttpMultipartMode.RFC6532参数的设定是为避免文件名为中文时乱码
            MultipartEntityBuilder builder = MultipartEntityBuilder.create().setMode(HttpMultipartMode.RFC6532);
            for (String param : params.keySet()){
                Object value = params.get(param);
                if(value instanceof File){
                    builder.addBinaryBody(param, (File) value, ContentType.MULTIPART_FORM_DATA,fileName);
                } else if(value instanceof Integer){
                    builder.addTextBody(param, value +"");
                } else {
                    builder.addTextBody(param, (String) value);
                }

            }
            HttpEntity entity = builder.build();
            httpPost.setEntity(entity);
            response = httpClient.execute(httpPost);// 执行提交
            HttpEntity responseEntity = response.getEntity();//接收调用外部接口返回的内容
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
                // 返回的内容都在content中
                content = responseEntity.getContent();
                // 定义BufferedReader输入流来读取URL的响应
                in = new BufferedReader(new InputStreamReader(content));
                String line;
                while ((line = in.readLine()) != null) {
                    result += line;
                }
            }
        }catch(Exception e) {
            log.error("上传文件失败:",e);
            return result;
        }finally {//处理结束后关闭httpclient的链接
            try {
                httpClient.close();
                content .close();
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是使用HttpClient上传文件的示例代码: ``` import java.io.File; import java.io.IOException; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.ContentType; import org.apache.http.entity.mime.MultipartEntityBuilder; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; public class FileUploader { public static void main(String[] args) { String url = "http://example.com/upload"; String filePath = "/path/to/file.txt"; // 创建HttpClient CloseableHttpClient httpClient = HttpClients.createDefault(); // 创建HttpPost请求 HttpPost httpPost = new HttpPost(url); // 创建multipart/form-data实体 File file = new File(filePath); HttpEntity httpEntity = MultipartEntityBuilder.create() .addBinaryBody("file", file, ContentType.DEFAULT_BINARY, file.getName()) .build(); // 设置请求实体 httpPost.setEntity(httpEntity); try { // 执行请求 HttpResponse response = httpClient.execute(httpPost); // 输出响应结果 System.out.println(response.getStatusLine().getStatusCode()); System.out.println(response.getEntity().getContent().toString()); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { // 关闭HttpClient try { httpClient.close(); } catch (IOException e) { e.printStackTrace(); } } } } ``` 在上面的示例代码中,我们使用了Apache HttpClient 4.x库来发送POST请求,并上传文件。我们首先创建了一个CloseableHttpClient实例,然后创建一个HttpPost实例,并设置请求实体为multipart/form-data类型的实体。 在实体中,我们添加了一个二进制文件体,它将文件添加到请求中。在这个例子中,我们使用了File类来表示文件,并用ContentType.DEFAULT_BINARY创建了一个ContentType实例。 最后,我们执行请求,并输出响应结果。注意,在使用HttpClient时,我们需要手动关闭HttpClient实例,以释放连接和资源。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值