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:
{ "startTime":"2013/09/09 11:00",
"endTime":"2013/09/09 13:00",
"pool": "webscr,paymentserv",
"regexs":["string1","string2"],
"searchMode":"simple",
}
To me this looks like a JSON object. So In my code I am trying to do the following
String url = "http://restAPIService.com/regex/request";
HttpClient client = HttpClientBuilder.create().build();
HttpPost post = new HttpPost(url);
List<BasicNameValuePair> urlParameters = new ArrayList<BasicNameValuePair>();
urlParameters.add(new BasicNameValuePair("startTime", startTime));
urlParameters.add(new BasicNameValuePair("endTime", endTime));
urlParameters.add(new BasicNameValuePair("pool", pool));
for (int i = 0; i < 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);
}
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.
What would be the best way to create a JSON object to send as the url parameters or the request body?
Help! Thanks!
Note: I also tried following something like this HTTP POST using JSON in Java 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"]