问题
We all pretty well know that the request and response format for JIRA REST API are in the form of JSON. I successfully retrieved the attachment details of the uploaded files using the url of type http://example.com:8080/jira/rest/api/2/attachment
.
I now need to work on file upload on to JIRA using the same REST API. I own a java client and its stated tat I need to post multipart input using MultiPartEntity
. I do not know how to submit a header of X-Atlassian-Token: nocheck
with the JSON request. Searching the documents I got only curl based request examples. Can anyone help me fixing this?
回答1:
I've done it this way, and it works:
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:
This is how i did it dependencies okhttp and 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());
}
来源:https://stackoverflow.com/questions/10913817/upload-files-in-jira-via-rest-api