0

我们都非常清楚 JIRA REST API 的请求和响应格式是 JSON 格式的。我使用 url 类型成功检索了上传文件的附件详细信息http://example.com:8080/jira/rest/api/2/attachment

我现在需要使用相同的 REST API 将文件上传到 JIRA。我拥有一个 java 客户端,它声明的 tat 我需要使用MultiPartEntity. 我不知道如何提交X-Atlassian-Token: nocheck带有 JSON 请求的标头。搜索文档我只得到了基于 curl 的请求示例。谁能帮我解决这个问题?

4

2 回答 2

1

我已经这样做了,它的工作原理:

public static void main( String[] args ) throws Exception {
    File f = new File(args[ 0 ]);
    String fileName = f.getName();
    String url = "https://[JIRA-SERVER]/rest/api/2/issue/[JIRA-KEY]/attachments";

    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpPost post = new HttpPost( url );
    post.setHeader( "Authorization", basicAuthHeader( "username", "password" ) );
    post.setHeader( "X-Atlassian-Token", "nocheck" );
    HttpEntity reqEntity = MultipartEntityBuilder.create()
            .setMode( HttpMultipartMode.BROWSER_COMPATIBLE )
            .addBinaryBody( "file",
                new FileInputStream( f ),
                ContentType.APPLICATION_OCTET_STREAM,
                f.getName() )
            .build();
    post.setEntity( reqEntity );
    post.setHeader( reqEntity.getContentType() );
    CloseableHttpResponse response = httpClient.execute( post );
}

public static String basicAuthHeader( String user, String pass ) {
    if ( user == null || pass == null ) return null;
    try {
        byte[] bytes = ( user + ":" + pass ).getBytes( "UTF-8" );
        String base64 = DatatypeConverter.printBase64Binary( bytes );
        return "Basic " + base64;
    }
    catch ( IOException ioe ) {
        throw new RuntimeException( "Stop the world, Java broken: " + ioe, ioe );
    }
}
于 2016-07-14T15:43:54.883 回答
1

这就是我做依赖okhttp和okio的方式

private static void upload(File file) throws Exception{
    final String address = "https://domain/rest/api/2/issue/issueId/attachments";
    final OkHttpClient okHttpClient = new OkHttpClient();
    final RequestBody formBody = new MultipartBody.Builder()
            .setType(MultipartBody.FORM)
            .addFormDataPart("file", file.getName(),
                    RequestBody.create(MediaType.parse("text/plain"), file))
            .build();
    final Request request = new Request.Builder().url(address).post(formBody)
            .addHeader("X-Atlassian-Token", "no-check")
            .addHeader("Authorization", "Basic api_token_from_your_account")
            .build();
    final Response response = okHttpClient.newCall(request).execute();
    System.out.println(response.code() + " => " + response.body().string());
}
于 2018-06-30T13:25:02.417 回答