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

Harsh Vardhan
Giga Patron

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



replace to



  HttpPost httpPost = new HttpPost("<your instance URL>");


Eg: <your instance URL>=https://dev14202.service-now.com



check the link below.


Attachment API - POST /now/attachment/file


Attachment API




you can try with https://<your url>/api/now/table/ecc_queue   also.



Thanks,


Harshvardhan




arjun6080
Kilo Explorer

Yes , I am using my service now instance URL with credentials.



Service now version - Istanbul



Also I have tried with :



String postData = "{\"agent\":\"AttachmentCreator\",\"topic\":\"AttachmentCreator\",,\"name\":\"sample.GIF:application/GIF\",\"source\":\"u_bp_portal:a6f97fb64ffe3200b01d8ab18110c75b\",\"payload\":\"/Rest_Works/WebContent/sample.GIF\"}";



Still no lucks



Anyone please help on this....


Hi Mallikarjun,



Can you paste the entire code so I can have a look?


after changing the URL, are you still getting the "HTTP/1.1 400 Bad Request".




Thanks,


Harshvardhan


Saif2
Kilo Contributor

Hi Arun,

 

Need your help, I am trying the achieve the same what you were trying, can you please share me the API's  (imports) that you have used for this file upload using binary.

 

 

Thanks

Sai007