java - 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,并且必须使用相同的编码上传。亲切的问候。
解决方案
推荐阅读
- firebase - Firebase 动态链接和托管在同一(自定义)域上
- amazon-web-services - 通过 DynamoDB 建模帖子和主题
- string - 如何在 Haskell 中转换 Integer in String 和 String in Integer?
- javascript - 如何在 React Js 中添加 Firebase Firestore 文档自动生成的 ID 添加到集合中的自定义数据字段
- vue.js - 为什么我的 Vue 应用程序添加到 index.html 中的我的 favicon 引用?
- c - 在 C 中显示合同工时和加班时间
- sql - 在 Salesforce SQL (SOQL) 中查询包含 JOINS 的子查询
- android - React-Native:在 Android 10 和 9(API 28 和 29)dalvik.system.BaseDexClassLoader.findClass 上崩溃
- firebase - Flutter firebase 查询快照错误:“未处理的异常:错误状态:无元素”
- contentful - 获取“您发送的正文包含未知密钥。” 尝试创建内容丰富的条目时