我試圖上傳一個附件到zendesk。從API文檔你必須使用用java上傳一個附件到zendesk
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}
}
}
這不是一個完整的例子,雖然對不對?合乎邏輯的下一步是以某種方式使上載在給定票證上可用。 –