httpclient上传文件结果为错误的文件

时间:2018-10-23 09:17:35

标签: java apache-httpclient-4.x

我正在使用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,并且必须使用相同的编码上传。 亲切的问候。

0 个答案:

没有答案