【问题标题】:upload files in JIRA via REST API通过 REST API 在 JIRA 中上传文件
【发布时间】:2012-06-06 12:01:21
【问题描述】:

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

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

【问题讨论】:

标签: json rest attachment jira


【解决方案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 );
    }
}

【讨论】:

    【解决方案2】:

    这就是我如何依赖 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());
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-10
      • 2021-09-18
      • 2021-06-07
      • 1970-01-01
      • 1970-01-01
      • 2017-11-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多