首页 > 解决方案 > httpclient 上传文件会导致文件损坏

问题描述

我正在使用 apache httpclient 将文件上传到服务器。我需要使用基本身份验证(用户名和密码)。然而,在 200 的响应中,服务器日志显示该文件丢失了一些数据。

public static String pushdata() throws FileNotFoundException, UnsupportedEncodingException {
    File file = new File("/home/mohamed/atomtest.txt");
    CredentialsProvider provider = new BasicCredentialsProvider();
    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("user", "pass");
    provider.setCredentials(AuthScope.ANY, credentials);
    HttpClient httpclient = HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build();
    HttpEntity data = MultipartEntityBuilder.create().setMode(HttpMultipartMode.BROWSER_COMPATIBLE).addBinaryBody("file", file).build();
    HttpUriRequest request = RequestBuilder.post("link").setEntity(data).build();
    ResponseHandler<String> responseHandler = response -> {
        int status = response.getStatusLine().getStatusCode();
        System.out.println(status);
        if (status >= 200 && status < 300) {
            HttpEntity entity = response.getEntity();
            String entityString = EntityUtils.toString(entity);
            System.out.println(entityString);
            return entityString;
        } else {
            throw new ClientProtocolException("Unexpected response status: " + status);
        }
    };
    String responseBody = "pushDATA";
    try {
        responseBody = httpclient.execute(request, responseHandler);

    } catch (IOException ex) {
        System.out.println(ex.toString());
    }
    return responseBody;
}

该文件保存为 UTF-16,并且必须使用相同的编码上传。亲切的问候。

标签: javaapache-httpclient-4.x

解决方案


推荐阅读