【发布时间】:2017-12-01 16:55:16
【问题描述】:
我目前正在尝试找出与此 curl 命令等效的 Java:
curl -X POST -u username:password -H "X-Atlassian-Token: no-check" http://example.com/rest/api/1.0/projects/STASH/avatar.png -F avatar=@avatar.png
任何帮助将不胜感激。
到目前为止,我已经成功使用了 Apache HTTP 库。下面是我成功使用的 POST 请求示例。然而,这个例子相当于这个 curl 命令:
curl -X POST -u username:password -H "Content-type: application/json" --data '{\"name\":\"projectName\", \"key\":\"KEY\", \"description\":\"good?\"}' "http://localhost:7990/rest/api/1.0/projects"
和java等价物:
// initialize connection
CloseableHttpClient client = HttpClients.createDefault();
HttpPost post = new HttpPost("http://localhost:7990/rest/api/1.0/projects")
try
{
// create a request using the input
StringEntity request = new StringEntity("{\"name\":\"projectName\", \"key\":\"KEY\", \"description\":\"good?\"}",ContentType.APPLICATION_JSON);
post.setEntity(request);
// add credentials to the header in order to get authorization
String credentials = username + ":" + password
byte[] encodedCredentials = Base64.encodeBase64(credentials.getBytes("UTF-8"));
String header = "Basic " + new String(encodedCredentials);
post.addHeader("Authorization",header);
// execute the request using the POST method
client.execute(post);
}
catch(Exception e)
{
// nada
}
finally
{
// close the connection
post.releaseConnection();
}
这是我为了模仿我第一次提到的 curl 命令而想出的:
// initialize connection
CloseableHttpClient client = HttpClients.createDefault();
HttpPost post = new HttpPost(HOST_URL + uri);
try
{
// create a request using the input
File avatar = new File("avatar.png")
FileBody uploadFilePart = new FileBody(avatar);
MultipartEntity request = new MultipartEntity();
request.addPart("upload-file", uploadFilePart);
post.setEntity(request);
// add credentials to the header in order to get authorization
byte[] encodedCredentials = Base64.encodeBase64(credentials.getBytes("UTF-8"));
String header = "Basic " + new String(encodedCredentials);
post.addHeader("Authorization",header);
// add the other header peice
post.addHeader("X-Atlassian-Token","no-check");
// execute the request
client.execute(post);
}
catch(Exception e)
{
// nada
}
finally
{
// close the connection
post.releaseConnection();
}
我认为它只是让我绊倒的文件上传部分。我知道原始 curl 请求有效,我已经在 git bash 中成功运行它。
在寻找上传文件的正确方法时,我遇到了使用不同版本的多部分数据的示例,例如 MultipartEntityBuilder 或 MultipartRequestEntity。但到目前为止,我还没有成功(这并不是说他们错了,我只是不知道自己在做什么)。
【问题讨论】:
标签: java apache curl bitbucket-api