How to convert this curl request to Http post request for file upload in java?












0















Following is my curl request:



curl -X POST --data-urlencode 'data1@/Users/Documents/file.csv' http://localhost:8000/predict


Following is my equivalent Java implementation.



String filePath = inputFilePath;
String url = inputUrl;
File file = new File(filePath);
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost uploadFile = new HttpPost(inputUrl);
uploadFile.addHeader("content-type", "application/x-www-form-urlencoded;charset=utf-8");

MultipartEntityBuilder builder = MultipartEntityBuilder.create();

FileBody fileBody = new FileBody(new File(inputFilePath));

HttpEntity reqEntity = MultipartEntityBuilder.create()
.addPart("data1", fileBody)
.build();


uploadFile.setEntity(reqEntity);
CloseableHttpResponse response = null;
try {
response = httpClient.execute(uploadFile);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}


I am trying to invoke my R Rest API endpoint from my Java HTTP post.



#* @post /predict
mypredict <- function(data1) {
print(data1)

}


(1) Is my equivalent Java HTTP Post request correct?
(2) I am able to invoke the R rest endpoint using my curl command. But for some reason when i sent the POST request through my Java code, i see that data1 is not being passed as part of post request. I see this error in R.



<simpleError in print(data1): argument "data1" is missing, with no default>


I feel my Java equivalent curl implementation is wrong. Can someone help?










share|improve this question





























    0















    Following is my curl request:



    curl -X POST --data-urlencode 'data1@/Users/Documents/file.csv' http://localhost:8000/predict


    Following is my equivalent Java implementation.



    String filePath = inputFilePath;
    String url = inputUrl;
    File file = new File(filePath);
    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpPost uploadFile = new HttpPost(inputUrl);
    uploadFile.addHeader("content-type", "application/x-www-form-urlencoded;charset=utf-8");

    MultipartEntityBuilder builder = MultipartEntityBuilder.create();

    FileBody fileBody = new FileBody(new File(inputFilePath));

    HttpEntity reqEntity = MultipartEntityBuilder.create()
    .addPart("data1", fileBody)
    .build();


    uploadFile.setEntity(reqEntity);
    CloseableHttpResponse response = null;
    try {
    response = httpClient.execute(uploadFile);
    } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }


    I am trying to invoke my R Rest API endpoint from my Java HTTP post.



    #* @post /predict
    mypredict <- function(data1) {
    print(data1)

    }


    (1) Is my equivalent Java HTTP Post request correct?
    (2) I am able to invoke the R rest endpoint using my curl command. But for some reason when i sent the POST request through my Java code, i see that data1 is not being passed as part of post request. I see this error in R.



    <simpleError in print(data1): argument "data1" is missing, with no default>


    I feel my Java equivalent curl implementation is wrong. Can someone help?










    share|improve this question



























      0












      0








      0








      Following is my curl request:



      curl -X POST --data-urlencode 'data1@/Users/Documents/file.csv' http://localhost:8000/predict


      Following is my equivalent Java implementation.



      String filePath = inputFilePath;
      String url = inputUrl;
      File file = new File(filePath);
      CloseableHttpClient httpClient = HttpClients.createDefault();
      HttpPost uploadFile = new HttpPost(inputUrl);
      uploadFile.addHeader("content-type", "application/x-www-form-urlencoded;charset=utf-8");

      MultipartEntityBuilder builder = MultipartEntityBuilder.create();

      FileBody fileBody = new FileBody(new File(inputFilePath));

      HttpEntity reqEntity = MultipartEntityBuilder.create()
      .addPart("data1", fileBody)
      .build();


      uploadFile.setEntity(reqEntity);
      CloseableHttpResponse response = null;
      try {
      response = httpClient.execute(uploadFile);
      } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
      }


      I am trying to invoke my R Rest API endpoint from my Java HTTP post.



      #* @post /predict
      mypredict <- function(data1) {
      print(data1)

      }


      (1) Is my equivalent Java HTTP Post request correct?
      (2) I am able to invoke the R rest endpoint using my curl command. But for some reason when i sent the POST request through my Java code, i see that data1 is not being passed as part of post request. I see this error in R.



      <simpleError in print(data1): argument "data1" is missing, with no default>


      I feel my Java equivalent curl implementation is wrong. Can someone help?










      share|improve this question
















      Following is my curl request:



      curl -X POST --data-urlencode 'data1@/Users/Documents/file.csv' http://localhost:8000/predict


      Following is my equivalent Java implementation.



      String filePath = inputFilePath;
      String url = inputUrl;
      File file = new File(filePath);
      CloseableHttpClient httpClient = HttpClients.createDefault();
      HttpPost uploadFile = new HttpPost(inputUrl);
      uploadFile.addHeader("content-type", "application/x-www-form-urlencoded;charset=utf-8");

      MultipartEntityBuilder builder = MultipartEntityBuilder.create();

      FileBody fileBody = new FileBody(new File(inputFilePath));

      HttpEntity reqEntity = MultipartEntityBuilder.create()
      .addPart("data1", fileBody)
      .build();


      uploadFile.setEntity(reqEntity);
      CloseableHttpResponse response = null;
      try {
      response = httpClient.execute(uploadFile);
      } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
      }


      I am trying to invoke my R Rest API endpoint from my Java HTTP post.



      #* @post /predict
      mypredict <- function(data1) {
      print(data1)

      }


      (1) Is my equivalent Java HTTP Post request correct?
      (2) I am able to invoke the R rest endpoint using my curl command. But for some reason when i sent the POST request through my Java code, i see that data1 is not being passed as part of post request. I see this error in R.



      <simpleError in print(data1): argument "data1" is missing, with no default>


      I feel my Java equivalent curl implementation is wrong. Can someone help?







      java rest curl






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 19 '18 at 8:11









      hrbrmstr

      60.3k687148




      60.3k687148










      asked Nov 19 '18 at 6:42









      CloudCloud

      2915




      2915
























          1 Answer
          1






          active

          oldest

          votes


















          1














          You specify content-type application/x-www-form-urlencoded (as curl does for this case) but supply an actual body (entity) that corresponds to multipart/form-data which is radically different. Instead use URLEncodedFormEntity containing (for your case) one NameValuePair something like this:



          byte contents = Files.readAllBytes (new File(filepath).toPath());
          List<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>();
          list.add(new BasicNameValuePair("data1", new String(contents,charset));
          uploadFile.setEntity(new UrlEncodedFormEntity (list));


          And you don't need addHeader("content-type",...) because setting the entity automatically supplies the content-type header (and content-length).






          share|improve this answer
























          • Thank you. It is working now.

            – Cloud
            Nov 19 '18 at 17:04











          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53369539%2fhow-to-convert-this-curl-request-to-http-post-request-for-file-upload-in-java%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          1














          You specify content-type application/x-www-form-urlencoded (as curl does for this case) but supply an actual body (entity) that corresponds to multipart/form-data which is radically different. Instead use URLEncodedFormEntity containing (for your case) one NameValuePair something like this:



          byte contents = Files.readAllBytes (new File(filepath).toPath());
          List<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>();
          list.add(new BasicNameValuePair("data1", new String(contents,charset));
          uploadFile.setEntity(new UrlEncodedFormEntity (list));


          And you don't need addHeader("content-type",...) because setting the entity automatically supplies the content-type header (and content-length).






          share|improve this answer
























          • Thank you. It is working now.

            – Cloud
            Nov 19 '18 at 17:04
















          1














          You specify content-type application/x-www-form-urlencoded (as curl does for this case) but supply an actual body (entity) that corresponds to multipart/form-data which is radically different. Instead use URLEncodedFormEntity containing (for your case) one NameValuePair something like this:



          byte contents = Files.readAllBytes (new File(filepath).toPath());
          List<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>();
          list.add(new BasicNameValuePair("data1", new String(contents,charset));
          uploadFile.setEntity(new UrlEncodedFormEntity (list));


          And you don't need addHeader("content-type",...) because setting the entity automatically supplies the content-type header (and content-length).






          share|improve this answer
























          • Thank you. It is working now.

            – Cloud
            Nov 19 '18 at 17:04














          1












          1








          1







          You specify content-type application/x-www-form-urlencoded (as curl does for this case) but supply an actual body (entity) that corresponds to multipart/form-data which is radically different. Instead use URLEncodedFormEntity containing (for your case) one NameValuePair something like this:



          byte contents = Files.readAllBytes (new File(filepath).toPath());
          List<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>();
          list.add(new BasicNameValuePair("data1", new String(contents,charset));
          uploadFile.setEntity(new UrlEncodedFormEntity (list));


          And you don't need addHeader("content-type",...) because setting the entity automatically supplies the content-type header (and content-length).






          share|improve this answer













          You specify content-type application/x-www-form-urlencoded (as curl does for this case) but supply an actual body (entity) that corresponds to multipart/form-data which is radically different. Instead use URLEncodedFormEntity containing (for your case) one NameValuePair something like this:



          byte contents = Files.readAllBytes (new File(filepath).toPath());
          List<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>();
          list.add(new BasicNameValuePair("data1", new String(contents,charset));
          uploadFile.setEntity(new UrlEncodedFormEntity (list));


          And you don't need addHeader("content-type",...) because setting the entity automatically supplies the content-type header (and content-length).







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 19 '18 at 12:01









          dave_thompson_085dave_thompson_085

          13k11631




          13k11631













          • Thank you. It is working now.

            – Cloud
            Nov 19 '18 at 17:04



















          • Thank you. It is working now.

            – Cloud
            Nov 19 '18 at 17:04

















          Thank you. It is working now.

          – Cloud
          Nov 19 '18 at 17:04





          Thank you. It is working now.

          – Cloud
          Nov 19 '18 at 17:04


















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53369539%2fhow-to-convert-this-curl-request-to-http-post-request-for-file-upload-in-java%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Biblatex bibliography style without URLs when DOI exists (in Overleaf with Zotero bibliography)

          ComboBox Display Member on multiple fields

          Is it possible to collect Nectar points via Trainline?