title: Java Spring Boot Rest API 400 Bad Request
body: <p>I am trying to make a async Rest API with Spring Boot.</p>
  <p>The Rest API receives http requests that have a json body with one value &quot;zahl&quot;, then it extracts that value, opens a socket and sends a tcp request with that number to a loadbalacer, that divides the Requests on different servers.
  They all make the same and calculate wheter the given number is a prime or not.
  If it is, it returns a String for example: &quot;(89) is prime: (true)&quot; or &quot;(10) is prime: false&quot;.
  The result goes back over the loadbalancer to the Rest API and finally to the client.</p>
  <p>That's how it should works.</p>
  <p>But for most requests I get Bad Request 400. Sometimes it works fine.</p>
  <p><a href="https://i.stack.imgur.com/34FUe.jpg" rel="nofollow noreferrer">400 Bad Request</a></p>
  <p>Therefore I tried to do the calculation directly instead of opening a socket and it works perfectly.</p>
  <p>So the problem is the Socket right?</p>
  <p>Here is my Code:</p>
  <pre><code>package javaRestApi;
  
  import java.io.IOException;
  import java.util.concurrent.CompletableFuture;
  
  import org.slf4j.Logger;
  import org.slf4j.LoggerFactory;
  import org.springframework.beans.factory.annotation.Autowired;
  import org.springframework.boot.SpringApplication;
  import org.springframework.boot.autoconfigure.SpringBootApplication;
  import org.springframework.boot.builder.SpringApplicationBuilder;
  import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
  import org.springframework.http.MediaType;
  import org.springframework.web.bind.annotation.GetMapping;
  import org.springframework.web.bind.annotation.PostMapping;
  import org.springframework.web.bind.annotation.RequestBody;
  import org.springframework.web.bind.annotation.RestController;
  
  @SpringBootApplication
  @RestController
  public class MyRestController extends SpringBootServletInitializer {
  
      private static Logger log = LoggerFactory.getLogger(MyRestController.class);
  
      public static void main(String[] args) {
          SpringApplication.run(MyRestController.class, args);
      }
  
      @Autowired
      private AsyncService service;
  
      @Override
      protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
          return builder.sources(MyRestController.class);
      }
      
      @PostMapping(value = &quot;/api/request/json&quot;, consumes = MediaType.APPLICATION_JSON_VALUE)
      public String jsonRequest(@RequestBody RequestModel body) throws IOException, Exception {
          log.info(&quot;new Request&quot;);
          CompletableFuture&lt;String&gt; result = service.isPrime(body.getZahl());
          log.info(&quot;Result: &quot; + result.get());
          return result.get();
      }
  }
  
  </code></pre>
  <pre><code>package javaRestApi;
  
  import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
  
  @JsonIgnoreProperties(ignoreUnknown=true)
  public class RequestModel {
      private String zahl;
      
      public void setZahl(String zahl) {
          this.zahl=zahl;
      }
      
      public String getZahl() {
          return zahl;
      }
  }
  </code></pre>
  <pre><code>package javaRestApi;
  
  import java.util.concurrent.Executor;
  
  import org.springframework.context.annotation.Bean;
  import org.springframework.context.annotation.Configuration;
  import org.springframework.scheduling.annotation.EnableAsync;
  import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
  
  @Configuration
  @EnableAsync
  public class AsyncConfiguration {
      
      @Bean(name = &quot;asyncExecutor&quot;)
      public Executor asyncExecutor() {
          ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
          executor.setCorePoolSize(2);
          executor.setMaxPoolSize(2);
          executor.setQueueCapacity(100);
          executor.setThreadNamePrefix(&quot;AsyncThread-&quot;);
          executor.initialize();
          return executor;
      }
  }
  </code></pre>
  <p>And finally the class where I create the Socket...</p>
  <pre><code>package javaRestApi;
  
  import java.io.BufferedReader;
  import java.io.IOException;
  import java.io.InputStreamReader;
  import java.io.OutputStreamWriter;
  import java.io.PrintWriter;
  import java.util.concurrent.CompletableFuture;
  
  import javax.net.SocketFactory;
  
  import java.net.Socket;
  import org.springframework.scheduling.annotation.Async;
  import org.springframework.stereotype.Service;
  
  @Service
  public class AsyncService {
  
      @Async(&quot;asyncExecutor&quot;)
      public CompletableFuture&lt;String&gt; isPrime(String zahl) throws IOException, Exception {
          
          //direct calcualtion
          int z = Integer.parseInt(zahl); 
          if(prime(z))
              return CompletableFuture.completedFuture(&quot;&quot; + z + &quot; is prime&quot;);
          else 
              return CompletableFuture.completedFuture(&quot;&quot; + z + &quot; is no prime&quot;);
          
          //with Tcp Connection
          //return CompletableFuture.completedFuture(&quot;3&quot;/*tcpClient(zahl)*/);
      }
      
      //local prime calculation
      private static boolean prime(int zahl) {
          for(int i = 2; i&lt;zahl; i++) {
                if(zahl % i == 0) { 
                    return false;
                }
          }
          return true;
      }
      
      // TCP connection to load balancer
      private static String tcpClient(String zahl) throws IOException, Exception {
          java.net.Socket socket = SocketFactory.getDefault().createSocket(&quot;localhost&quot;, 12345);
          senden(socket, zahl);
          return lesen(socket);
      }
  
      // send the value to Socket
      static void senden(java.net.Socket socket, String zahl) throws IOException {
          PrintWriter prwr = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
          prwr.print(zahl);
          prwr.flush();
      }
  
      // get the result from the socket
      static String lesen(java.net.Socket socket) throws IOException {
          int Buflength = 40;
          BufferedReader bufR = new BufferedReader(new InputStreamReader(socket.getInputStream()));
          char[] buf = new char[Buflength];
          int anzZeichen = bufR.read(buf, 0, Buflength);
          String retString = new String(buf, 0, anzZeichen);
          return retString;
      }
  }
  </code></pre>
  <p>And here the Stacktrace.</p>
  <pre><code>
    .   ____          _            __ _ _
   /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
  ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
   \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
    '  |____| .__|_| |_|_| |_\__, | / / / /
   =========|_|==============|___/=/_/_/_/
   :: Spring Boot ::        (v2.3.1.RELEASE)
  
  2020-06-26 20:22:36.106  INFO 71152 --- [           main] javaRestApi.MyRestController             : Starting MyRestController on DESKTOP-FVOQ69M with PID 71152 (C:\Users\Fill07\Desktop\javaRestApi\target\classes started by Fill07 in C:\Users\Fill07\Desktop\javaRestApi)
  2020-06-26 20:22:36.110  INFO 71152 --- [           main] javaRestApi.MyRestController             : No active profile set, falling back to default profiles: default
  WARNING: An illegal reflective access operation has occurred
  WARNING: Illegal reflective access by org.springframework.cglib.core.ReflectUtils (file:/C:/Users/Fill07/.m2/repository/org/springframework/spring-core/5.2.7.RELEASE/spring-core-5.2.7.RELEASE.jar) to method java.lang.ClassLoader.defineClass(java.lang.String,byte[],int,int,java.security.ProtectionDomain)
  WARNING: Please consider reporting this to the maintainers of org.springframework.cglib.core.ReflectUtils
  WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
  WARNING: All illegal access operations will be denied in a future release
  2020-06-26 20:22:37.870  INFO 71152 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
  2020-06-26 20:22:37.884  INFO 71152 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
  2020-06-26 20:22:37.884  INFO 71152 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.36]
  2020-06-26 20:22:38.213  INFO 71152 --- [           main] org.apache.jasper.servlet.TldScanner     : At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
  2020-06-26 20:22:38.225  INFO 71152 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
  2020-06-26 20:22:38.225  INFO 71152 --- [           main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 2041 ms
  2020-06-26 20:22:38.356  INFO 71152 --- [           main] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService
  2020-06-26 20:22:38.358  INFO 71152 --- [           main] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'asyncExecutor'
  2020-06-26 20:22:38.845  INFO 71152 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
  2020-06-26 20:22:38.860  INFO 71152 --- [           main] javaRestApi.MyRestController             : Started MyRestController in 3.385 seconds (JVM running for 3.941)
  2020-06-26 20:22:40.830  INFO 71152 --- [nio-8080-exec-2] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring DispatcherServlet 'dispatcherServlet'
  2020-06-26 20:22:40.830  INFO 71152 --- [nio-8080-exec-2] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'
  2020-06-26 20:22:40.841  INFO 71152 --- [nio-8080-exec-2] o.s.web.servlet.DispatcherServlet        : Completed initialization in 11 ms
  2020-06-26 20:22:40.977  INFO 71152 --- [nio-8080-exec-2] javaRestApi.MyRestController             : new Request
  2020-06-26 20:22:41.013  INFO 71152 --- [nio-8080-exec-2] javaRestApi.MyRestController             : Result: HTTP/1.1 400 Bad Request
  Connection: cl
  </code></pre>
  <p>I don't understand what is wrong, i mean sometimes it works.</p>
  <p>How can I fix it?</p>
  <p>Is it maybe a problem with Tomcat?</p>
  <p>Thanks for any advice.</p>