我正在尝试将附件上传到zendesk。从您必须使用的 API 文档中
curl -u username:password -H "Content-Type: application/binary" \
--data-binary @file.dat -X POST \
"https://helpdesk.zendesk.com/api/v2/uploads.json?filename=myfile.dat&token= {optional_token}"
我正在尝试用 java 做同样的事情。我可以上传文件并接收正确的 json 响应。但是,如果我在 zendesk 服务器上打开文件,则无法识别该文件。如果我从命令行使用 curl 上传相同的文件,一切正常。我在这里做错了什么?这是我用来上传文件的java代码。
public static void main(String[] args) throws IOException {
File file = new File("C:\\Users\\user\\Documents\\zendesk2\\Zendesk\\src\\main\\resources\\scrat.jpg");
try {
MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
multipartEntity.addPart("filename", new StringBody(file.getName()));
FileBody fileBody = new FileBody(file, "application/octet-stream");
multipartEntity.addPart("attachment", fileBody);
// -u admin:password
Credentials credentials = new UsernamePasswordCredentials("username", "passw");
DefaultHttpClient httpClient = new DefaultHttpClient();
httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY, credentials);
// -X POST
HttpPost httpPost = new HttpPost("https://testserver.zendesk.com/api/v2/uploads.json");
// @ - absolute path
httpPost.setEntity(multipartEntity);
// process response
HttpResponse response = httpClient.execute(httpPost);
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
long len = resEntity.getContentLength();
if (len != -1 && len < 2048) {
// this result is being parsed with gson....
System.out.println(EntityUtils.toString(resEntity));
} else {
// Stream content out
}
}
httpClient.getConnectionManager().shutdown();
} catch (Exception e) {
//-f, fail silently}
}
}