Attachment Upload Rest API - JAVA

arjun6080
Kilo Explorer

Hello ,

I am trying to upload an attachment to an ticket using below JAVA code.

String postData = "{\"table_name\":\"u_portal\",\"table_sys_id\":\"091feee8ab18110c778\",\"uploadFile\":\"/ServiceNow_Rest/src/com/servicenow/integration/upload1.JPG\"}";

  CredentialsProvider credsProvider = new BasicCredentialsProvider();

  credsProvider.setCredentials(new AuthScope(new HttpHost("service-now.com")),

  new UsernamePasswordCredentials("name", "pwd"));

  CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();

  try {

  HttpPost httpPost = new HttpPost("https://service-now.com/api/now/attachment/upload");

  httpPost.setHeader("Accept", "application/json");

  httpPost.setHeader("Content-Type", "multipart/form-data");

  HttpEntity entity = new ByteArrayEntity(postData.getBytes("utf-8"));

  httpPost.setEntity(entity);

  System.out.println("Executing request " + httpPost.getRequestLine());

  CloseableHttpResponse response = httpclient.execute(httpPost);

  try {

  System.out.println("----------------------------------------");

  System.out.println(response.getStatusLine());

  String responseBody = EntityUtils.toString(response.getEntity());

  System.out.println(responseBody);

....

Getting

HTTP/1.1 400 Bad Request

{"error":{"detail":null,"message":"Failed to create the attachment. File part might be missing in the request."},"status":"failure"}

can someone help on this ?

Regards,

13 REPLIES 13

Hi All


i am also trying to upload an attachment from 3rd party system to Servicenow usin REST API.


I am getting the response like this from 3rd party -


����� JFIF�     �`�`���� �Exif��MM�*��� �   ;� ���


�� J�i� ��� �� X��� ��� �� x� � ��




Can some one tell me how am i going to convert it to required format and save it. I do the file name also and which field it needs to be added in servicenow in separate GET method.



Please help me what should be my steps?



brajendragupta@kpmg.com       Can you please help on this?


Surya


Can you elaborate what are you trying to achieve?


if third party is posting attachment to service-now then use OOB attachment API to post file directly to target record.


Saif2
Kilo Contributor

Please provide me the import/API's used for the above code and appreciate if you could copy the whole code.

 

Thanks
Sai007

Sashi K1
Kilo Guru

This is working code, that pushes a File to ServiceNow record. Above code has errors, below one tested to work all the time. Make sure to replace <..> with proper strings eg> userid or password or instance name. 

Import all Jars as mentioned below

 

Good luck!

===============================

 

import java.io.File;

 

import org.apache.http.Header;

import org.apache.http.HttpEntity;

import org.apache.http.HttpResponse;

import org.apache.http.auth.AuthScope;

import org.apache.http.auth.UsernamePasswordCredentials;

import org.apache.http.client.CredentialsProvider;

import org.apache.http.client.methods.HttpPost;

import org.apache.http.entity.ContentType;

import org.apache.http.entity.mime.HttpMultipartMode;

import org.apache.http.entity.mime.MultipartEntityBuilder;

import org.apache.http.entity.mime.content.StringBody;

import org.apache.http.impl.client.BasicCredentialsProvider;

import org.apache.http.impl.client.CloseableHttpClient;

import org.apache.http.impl.client.HttpClients;

import org.apache.http.util.EntityUtils;

 

public class UploadFile {

public static void main(String[] args) throws Exception {

 

try {

 

System.out.println("Starting Post Request.....");

 

CredentialsProvider credsProvider = new BasicCredentialsProvider();

 

//make sure credentials given have right permissions on the target table. I used Admin for testing

UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("<userid>", "<password>");

 

credsProvider.setCredentials(AuthScope.ANY, credentials);

 

CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();

 

HttpPost httppost = new HttpPost("https://<instance-name>.service-now.com/api/now/v1/attachment/upload");

 

httppost.setHeader("Accept", "application/json");

// build multipart request

String textFileName = "/Users/Ajay/Desktop/test/test.txt";

File file = new File(textFileName);

MultipartEntityBuilder builder = MultipartEntityBuilder.create();

builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); 

StringBody stringBody1 = new StringBody("<table>", ContentType.MULTIPART_FORM_DATA);

StringBody stringBody2 = new StringBody("<record_sys_id>", ContentType.MULTIPART_FORM_DATA);

HttpEntity reqEntity = (builder

.addPart("table_sys_id",stringBody2)

.addPart("table_name",stringBody1)

.addBinaryBody("uploadFile", file, ContentType.DEFAULT_BINARY, file.getName())).build();

 

httppost.setEntity(reqEntity);

// ---Print outgoing request---

Header[] headers = (Header[]) httppost.getAllHeaders();

//String content = EntityUtils.toString(entity);

System.out.println(httppost.toString());

for (Header header : headers) {

System.out.println(header.getName() + ": " + header.getValue());

}

 

System.out.println();

 

//System.out.println(content);

 

// ----execute http request

HttpResponse response = httpclient.execute(httppost);

System.out.println("HTTP POST response:");

System.out.println(response.getStatusLine());

String responseBody = EntityUtils.toString(response.getEntity());

System.out.println(responseBody);

} catch (Exception e) {

System.err.println("Unable to read file");

e.printStackTrace();

}

}

}