通过REST API在JIRA中上传文件

时间:2012-06-06 12:01:22

标签: json rest attachment jira

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

我现在需要使用相同的REST API处理文件上传到JIRA。我拥有一个java客户端及其声明我需要使用MultiPartEntity发布多部分输入。我不知道如何使用JSON请求提交X-Atlassian-Token: nocheck的标头。搜索文档我只得到基于curl的请求示例。任何人都可以帮我解决这个问题吗?

2 个答案:

答案 0 :(得分: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 );
    }
}

答案 1 :(得分: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());
}