Search code examples
javahttpcurljetty

How can I replicate this curl command using a Jetty request in java?


I have this curl command

curl -F 'client_id={client id}' \
-F 'client_secret={client secret}' \
-F 'code={temporary token}' \
-F 'grant_type=authorization_code' \
https://cloud.lightspeedapp.com/oauth/access_token.php

taken from https://developers.lightspeedhq.com/retail/authentication/access-token/

I'm trying to call this api using a jetty request in java. Here's what I've got so far.

URIBuilder uriBuilder = new URIBuilder("https://cloud.lightspeedapp.com")
  .setPath("/oauth/access_token.php");

MultiPartContentProvider contentProvider = new MultiPartContentProvider();
contentProvider.addFieldPart("grant_type", new StringContentProvider("authorization_code"), null);
contentProvider.addFieldPart("client_id", new StringContentProvider(lightspeedRId), null);
contentProvider.addFieldPart("client_secret", new StringContentProvider(lightspeedRSecret), null);
contentProvider.addFieldPart("code", new StringContentProvider(temporaryToken), null);
contentProvider.close();

Request request = httpClient.POST(uriBuilder.build())
  .content(contentProvider)
  .header("Content-Type", "multipart/form-data");

However, it's not working. I'm at a complete loss and not sure what I need to change here.

EDIT: I tried a FormContentProvider as well and got the same results.

Fields fields = new Fields();
fields.put("grant_type", "authorization_code");
fields.put("client_id", lightspeedRId);
fields.put("client_secret", lightspeedRSecret);
fields.put("code",temporaryToken);
FormContentProvider contentProvider = new FormContentProvider(fields);

Solution

  • Okay, turns out, the problem was the setting of the "Content-Type" header on the request at the end.

    Request request = httpClient.POST(uriBuilder.build())
      .content(contentProvider)
      .header("Content-Type", "multipart/form-data");
    

    Without that, it worked perfectly like this.

    URIBuilder uriBuilder = new URIBuilder("https://cloud.lightspeedapp.com")
      .setPath("/oauth/access_token.php");
    
    Fields fields = new Fields();
    fields.put("grant_type", "authorization_code");
    fields.put("client_id", lightspeedRId);
    fields.put("client_secret", lightspeedRSecret);
    fields.put("code",temporaryToken);
    FormContentProvider contentProvider = new FormContentProvider(fields);
    
    Request request = httpClient.POST(uriBuilder.build())
      .content(contentProvider);
    

    The reason I was setting that header in the first place was because of this part of the documentation.

    Content-Type falsehood in the docs

    So yeah, turns out Lightspeed just has terrible documentation. Let this be a cautionary tale.