0 Replies Latest reply: Sep 26, 2013 1:14 PM by SanchitJavaDev RSS

    Error while utilizing curl via HTTPClient

    SanchitJavaDev

      The following curl is working in Windows Environment to upload a CSV File over Server

       curl --user abc@xyz.com:testing --form file=@Testing.csv <URL>/data

      But when I'm trying to introduce the commons HTTPClient 4.x for this request, I'm facing the error:

      HTTP/1.1 500 Server Error

      From the code snippet I'm passing the file and its value inside the BasicNameValuePair. So, whenever I'm passing nothing like

      new BasicNameValuePair("file", "")

      the response is coming 200 Ok and obviously the content over the server gets replaced with Empty data.

      I got one success in passing the content in Text (the CSV received content) by using StringEntity like

      httpPost.setEntity(new StringEntity("a, b, c, d", "UTF-8"));

      , but its again giving me 2 thoughts:

      1. If I try to use the Text - I mostly face the Java Heap Space issue.
      2. I'm not able to pass the FileName from inside StringEntity- like
        new StringEntity("file=@Testing.csv")

       

      Please let me know what I'm doing wrong.

      This is the following code I'm using:

       

      CredentialsProvider credsProvider = new BasicCredentialsProvider();
          credsProvider.setCredentials(
              new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
              new UsernamePasswordCredentials("abc@xyz.com", "testing"));
          CloseableHttpClient httpclient = HttpClients.custom()
              .setDefaultCredentialsProvider(credsProvider).build();
          HttpPost httpPost = new HttpPost("<URL>/data");
                  
       // httpPost.setEntity((new StringEntity("a, b, c, d", "UTF-8"));
      
        
      List <NameValuePair> nvps = new ArrayList <NameValuePair>();        
      
          nvps.add(new BasicNameValuePair("file", "@Testing.csv"));
                  
          httpPost.setEntity(new UrlEncodedFormEntity(nvps));
          CloseableHttpResponse response2 = httpclient.execute(httpPost);
      
          try {
              System.out.println(response2.getStatusLine());
              HttpEntity entity2 = response2.getEntity();
              // do something useful with the response body
              // and ensure it is fully consumed
              EntityUtils.consume(entity2);
          } finally {
                  response2.close();
          }