0

I have done lots of googling and trial and error but can't get this to work.

I am trying to send a HTTP POST request using JAVA that includes a file to be sent. This is the code I have tried that doesn't seem to work for some reason:

public void iSendARequestToAnAPI() throws Exception {

  //This is the httpClient that you will use to send your http request
  CloseableHttpClient httpClient = HttpClients.createDefault();
  HttpPost httpPost = new HttpPost("https://xxxxxxxxxxxxxxxxx/document");

  httpPost.setHeader("tolerance", "strict");
  httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
  httpPost.setHeader("Authorization", "Bearer xxxx");

  File file = new File("C:\\Matt\\GBG\\drivinglicence.jpg");

  HttpEntity entity = MultipartEntityBuilder
    .create()
    .addBinaryBody("file", file, ContentType.create("image/jpeg"), file.getName())
    .build();

  httpPost.setEntity(entity);

  //Send the request
  CloseableHttpResponse response = httpClient.execute(httpPost);

  //Close the http client
  httpClient.close();

  }
}

For info, this is the curl command taken from a Postman request that works:

curl -X POST \
  https://idaasstaging.gbgplc.com/verify/documents/v2/document \
  -H 'Content-Type: application/x-www-form-urlencoded' \
  -H 'Postman-Token: 82966229-2e00-4309-a428-be66b4e8d8ca' \
  -H 'cache-control: no-cache' \
  -H 'content-type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW' \
  -H 'tolerance: strict' \
  -F file=@/C:/Matt/GBG/uk-driving-licence.jpg

Anyone know what I'm doing wrong?

I'm getting the following response, I'm not sure what it means. Maybe I am just being blocked? Works fine with a Postman request though:

<html style="height:100%"><head><META NAME="ROBOTS" CONTENT="NOINDEX, NOFOLLOW"><meta name="format-detection" content="telephone=no"><meta name="viewport" content="initial-scale=1.0"><meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"></head><body style="margin:0px;height:100%"><iframe id="main-iframe" src="/_Incapsula_Resource?CWUDNSAI=22&xinfo=12-233465551-0%20NNNN%20RT%281570437116752%20119%29%20q%280%200%20-1%20-1%29%20r%281%20-1%29%20B15%281%2c501%2c51%29%20U6&incident_id=801001040412185768-821262601053865612&edet=15&cinfo=010000003634" frameborder=0 width="100%" height="100%" marginheight="0px" marginwidth="0px">Request unsuccessful. Incapsula incident ID: 801001040412185768-821262601053865612</iframe></body></html>
Matt
  • 773
  • 2
  • 15
  • 30
  • "doesn't seem to work for some reason" Please provide the exact details of the problem/error. – OldProgrammer Oct 06 '19 at 19:15
  • Possible duplicate of [Http POST in Java (with file upload)](https://stackoverflow.com/questions/9692166/http-post-in-java-with-file-upload) – OldProgrammer Oct 06 '19 at 19:16
  • Just added more info to the question. I am receiving a strange Incapsula html response. I'm not sure what it means. Maybe I am just being blocked? – Matt Oct 07 '19 at 08:52

0 Answers0