title: Sending a JSON object to a rest service as a POST in JAVA
body: <p>Hi I am sort of new to Java and making POST request to urls. However I am trying to send a post request to a url that expects the body to look like this:</p>
  
  <pre><code>{ "startTime":"2013/09/09 11:00",
    "endTime":"2013/09/09 13:00",
    "pool": "webscr,paymentserv",
    "regexs":["string1","string2"],
    "searchMode":"simple",
  }
  </code></pre>
  
  <p>To me this looks like a JSON object. So In my code I am trying to do the following</p>
  
  <pre><code>    String url = "http://restAPIService.com/regex/request";
  
      HttpClient client = HttpClientBuilder.create().build();
      HttpPost post = new HttpPost(url);
  
      List&lt;BasicNameValuePair&gt; urlParameters = new ArrayList&lt;BasicNameValuePair&gt;();
      urlParameters.add(new BasicNameValuePair("startTime", startTime));
      urlParameters.add(new BasicNameValuePair("endTime", endTime));
      urlParameters.add(new BasicNameValuePair("pool", pool));
      for (int i = 0; i &lt; regexArray.length; i++) {
          urlParameters.add(new BasicNameValuePair("regexs[]",regexArray[i]));
     }
  
      post.setEntity(new UrlEncodedFormEntity(urlParameters));
      HttpResponse response = client.execute(post);
  
      BufferedReader rd = new BufferedReader(
                      new InputStreamReader(response.getEntity().getContent()));
  
      StringBuffer result = new StringBuffer();
      String line = "";
      while ((line = rd.readLine()) != null) {
          result.append(line);
      }
  </code></pre>
  
  <p>However when I run this code I get a response of 415. I think this is because this name value pair isn't creating a JSON objects, but I have no idea how to create a Json object in Java and documentation online has not helped. Presumably a basic name value pair would work but not all pairs are string string. Notice that the regexs field is an array of strings.</p>
  
  <p>What would be the best way to create a JSON object to send as the url parameters or the request body?</p>
  
  <p>Help! Thanks!</p>
  
  <p>Note: I also tried following something like this <a href="https://stackoverflow.com/questions/7181534/http-post-using-json-in-java">HTTP POST using JSON in Java</a> but I couldn't get it to work for specific purpose. If it helps my regexArray doesnt have to be an array (I only always have on regex so this field in the object will always be like this regexs: ["string1"]</p>