Java相当于curl命令

时间:2017-12-01 16:55:16

标签: java apache curl bitbucket-api

我目前正在尝试找出与此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。但到目前为止,我还没有取得任何成功(这并不是说他们错了,我只是不知道我在做什么)。

1 个答案:

答案 0 :(得分:0)

您可以使用java.net.URL和/或java.net.URLConnection.

URL url = new URL("http://stackoverflow.com");

try (BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"))) {
    for (String line; (line = reader.readLine()) != null;) {
        System.out.println(line);
    }
}

另请参阅Oracle关于此主题的简单教程。但它有点冗长。为了得到更简洁的代码,您可能需要考虑使用Apache HttpClient。

See